类org.apache.http.client.HttpClient源码实例Demo

下面列出了怎么用org.apache.http.client.HttpClient的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: keycloak   文件: ProductDatabaseClient.java
public static List<String> getProducts(HttpServletRequest req) throws Failure {
    KeycloakSecurityContext session = (KeycloakSecurityContext)req.getAttribute(KeycloakSecurityContext.class.getName());

    HttpClient client = new DefaultHttpClient();
    try {
        HttpGet get = new HttpGet(UriUtils.getOrigin(req.getRequestURL().toString()) + "/database/products");
        get.addHeader("Authorization", "Bearer " + session.getTokenString());
        try {
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Failure(response.getStatusLine().getStatusCode());
            }
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            try {
                return JsonSerialization.readValue(is, TypedList.class);
            } finally {
                is.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
public DCContentUploader upload() throws IOException
{
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type", "application/octet-stream");
    post.setEntity(new InputStreamEntity(content));

    HttpResponse httpResponse = client.execute(post);
    status = httpResponse.getStatusLine().getStatusCode();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    StreamUtils.copy(httpResponse.getEntity().getContent(), os);
    response = os.toString("UTF-8");
    headers = new HttpHeaders();
    for(Header header : httpResponse.getAllHeaders()) {
        headers.add(header.getName(), header.getValue());
    }
    post.releaseConnection();
    return this;
}
 
源代码3 项目: carbon-apimgt   文件: Util.java
public static String getUserInfo(ServerConfiguration serverConfiguration,
                                 AuthenticationToken token) throws IOException {

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet(serverConfiguration.getUserInfoUri());

    get.setHeader("Authorization", String.format("Bearer %s", token.getAccessTokenValue()));
    HttpResponse response = httpClient.execute(get);

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));

    String jsonString = "";
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        jsonString = jsonString + line;
    }
    bufferedReader.close();
    return jsonString;
}
 
源代码4 项目: keycloak   文件: RegistrationRecaptcha.java
protected boolean validateRecaptcha(ValidationContext context, boolean success, String captcha, String secret) {
    HttpClient httpClient = context.getSession().getProvider(HttpClientProvider.class).getHttpClient();
    HttpPost post = new HttpPost("https://www." + getRecaptchaDomain(context.getAuthenticatorConfig()) + "/recaptcha/api/siteverify");
    List<NameValuePair> formparams = new LinkedList<>();
    formparams.add(new BasicNameValuePair("secret", secret));
    formparams.add(new BasicNameValuePair("response", captcha));
    formparams.add(new BasicNameValuePair("remoteip", context.getConnection().getRemoteAddr()));
    try {
        UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
        post.setEntity(form);
        HttpResponse response = httpClient.execute(post);
        InputStream content = response.getEntity().getContent();
        try {
            Map json = JsonSerialization.readValue(content, Map.class);
            Object val = json.get("success");
            success = Boolean.TRUE.equals(val);
        } finally {
            content.close();
        }
    } catch (Exception e) {
        ServicesLogger.LOGGER.recaptchaFailed(e);
    }
    return success;
}
 
源代码5 项目: coolreader   文件: AppUtil.java
/**
 * 获取网址内容
 * @param url
 * @return
 * @throws Exception
 */
public static String getContent(String url) throws Exception{
    StringBuilder sb = new StringBuilder();
    
    HttpClient client = new DefaultHttpClient();
    HttpParams httpParams = client.getParams();
    //设置网络超时参数
    HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);
    HttpResponse response = client.execute(new HttpGet(url));
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);
        
        String line = null;
        while ((line = reader.readLine())!= null){
            sb.append(line + "/n");
        }
        reader.close();
    }
    return sb.toString();
}
 
源代码6 项目: IGUANA   文件: UPDATEWorker.java
private void setCredentials(UpdateProcessor exec) {
	if (exec instanceof UpdateProcessRemote && user != null && !user.isEmpty() && password != null
			&& !password.isEmpty()) {
		CredentialsProvider provider = new BasicCredentialsProvider();

		provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
				new UsernamePasswordCredentials(user, password));
		HttpContext httpContext = new BasicHttpContext();
		httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, provider);

		((UpdateProcessRemote) exec).setHttpContext(httpContext);
		HttpClient test = ((UpdateProcessRemote) exec).getClient();
		System.out.println(test);
	}

}
 
源代码7 项目: flashback   文件: FlashbackRunnerTest.java
@Test
public void testNotMatchMethod() throws IOException, InterruptedException {
  URL flashbackScene = getClass().getResource(FLASHBACK_SCENE_DIR);
  String rootPath = flashbackScene.getPath();
  SceneConfiguration sceneConfiguration = new SceneConfiguration(rootPath, SCENE_MODE, HTTP_SCENE);
  try (FlashbackRunner flashbackRunner = new FlashbackRunner.Builder().mode(SCENE_MODE)
      .sceneAccessLayer(
          new SceneAccessLayer(SceneFactory.create(sceneConfiguration), MatchRuleUtils.matchEntireRequest()))
      .build()) {
    flashbackRunner.start();
    HttpHost host = new HttpHost(PROXY_HOST, PROXY_PORT);
    String url = "http://www.example.org/";
    HttpClient client = HttpClientBuilder.create().setProxy(host).build();
    HttpPost post = new HttpPost(url);
    HttpResponse httpResponse = client.execute(post);
    Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), 400);
    Assert.assertTrue(EntityUtils.toString(httpResponse.getEntity())
        .contains("No Matching Request"));
  }
}
 
源代码8 项目: NLIWOD   文件: RunProducer.java
public static String stringToResource(String answer){
	try {
		ResponseToStringParser parser = new ResponseToStringParser();
		HttpClient client = HttpClientBuilder.create().build();
		URI uri = new URIBuilder().setScheme("http").setHost("dbpedia.org").setPath("/sparql")
				.setParameter("default-graph-uri", "http://dbpedia.org")
				.setParameter("query", "SELECT ?uri WHERE {?uri rdfs:label \"" + answer + "\"@en.}")
				.setParameter("format", "text/html")
				.setParameter("CXML_redir_for_subjs", "121")
				.setParameter("CSML_redir_for_hrefs", "")
				.setParameter("timeout", "30000")
				.setParameter("debug", "on")
				.build();
		HttpGet httpget = new HttpGet(uri);
		HttpResponse response = client.execute(httpget);
		Document doc;
		doc = Jsoup.parse(parser.responseToString(response));
	return doc.select("a").attr("href");
	} catch (IllegalStateException | IOException | URISyntaxException e) {
		e.printStackTrace();
		return "";
	}
	
	
}
 
源代码9 项目: wallpaper   文件: WallWrapperServiceMediator.java
public static String feedback_post(String content, String contact, String version, String system, String uuid) {
	String count = "";
	HttpClient httpClient = new DefaultHttpClient();
	HttpPost httpPost = new HttpPost("http://luhaojie.test.abab.com/index.php");//?picSize=320x510&imgSize=320x510
	List<BasicNameValuePair> valuePairs = new ArrayList<BasicNameValuePair>();
		valuePairs.add(new BasicNameValuePair("c", "AbabInterface_Sj"));
		valuePairs.add(new BasicNameValuePair("a", "Pic"));
		valuePairs.add(new BasicNameValuePair("param", "{\"content\":\"" + content + "\",\"system\":\"Android\",\"version\":\"" + version + "\",\"contact\":\"" + contact + "\",\"uuid\":\""+uuid+"\"}"));						
	try {
		httpPost.setEntity(new UrlEncodedFormEntity(valuePairs, "UTF-8"));
		httpPost.setHeader("Content-Type",
				"application/x-www-form-urlencoded; charset=utf-8");
	} catch (UnsupportedEncodingException e2) {
		e2.printStackTrace();
	}
	try {
		HttpResponse response = httpClient.execute(httpPost);
		count = EntityUtils.toString(response.getEntity(), "utf-8");
	
	} catch (Exception e1) {
		e1.printStackTrace();
	}
	return count;
	
}
 
private HttpResponse makeHTTPConnection() throws IOException, NullPointerException {
    if (fileURI == null) throw new NullPointerException("No file URI specified");

    HttpClient client = HttpClientBuilder.create().build();

    HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod();
    requestMethod.setURI(fileURI);

    BasicHttpContext localContext = new BasicHttpContext();

    if (null != urlParameters && (
            httpRequestMethod.equals(RequestType.PATCH) ||
                    httpRequestMethod.equals(RequestType.POST) ||
                    httpRequestMethod.equals(RequestType.PUT)
    )) {
        ((HttpEntityEnclosingRequestBase) requestMethod)
                .setEntity(new UrlEncodedFormEntity(urlParameters));
    }

    return client.execute(requestMethod, localContext);
}
 
public AbstractRestTemplateClient ignoreAuthenticateServer() {
    //backward compatible with android httpclient 4.3.x
    if(restTemplate.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            X509HostnameVerifier verifier = ignoreSslWarning ? new AllowAllHostnameVerifier() : new BrowserCompatHostnameVerifier();
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, verifier);
            HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
            ((HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory()).setHttpClient(httpClient);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Debug.error("the request factory " + restTemplate.getRequestFactory().getClass().getName() + " does not support ignoreAuthenticateServer");
    }
    return this;
}
 
源代码12 项目: AppServiceRestFul   文件: Util.java
private static HttpClient getNewHttpClient() { 
   try { 
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
       trustStore.load(null, null); 

       SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); 
       sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

       HttpParams params = new BasicHttpParams(); 
       HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
       HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

       SchemeRegistry registry = new SchemeRegistry(); 
       registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
       registry.register(new Scheme("https", sf, 443)); 

       ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 

       return new DefaultHttpClient(ccm, params); 
   } catch (Exception e) { 
       return new DefaultHttpClient(); 
   } 
}
 
源代码13 项目: product-ei   文件: SPARQLServiceTestCase.java
private boolean isExternalEndpointAvailable() throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    String url = "http://semantic.eea.europa.eu/sparql?query=";
    String query = "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX cr:<http://cr.eionet.europa.eu/ontologies/contreg.rdf#>\n"
            + "SELECT * WHERE {  ?bookmark a cr:SparqlBookmark;rdfs:label ?label} LIMIT 50";
    url = url + URLEncoder.encode(query, "UTF-8");
    HttpGet httpGet = new HttpGet(url);
    httpClient.getParams().setParameter("http.socket.timeout", 300000);
    httpGet.setHeader("Accept", "text/xml");
    HttpResponse httpResponse = httpClient.execute(httpGet);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
        return true;
    }
    return false;
}
 
源代码14 项目: olingo-odata4   文件: AbstractODataRequest.java
/**
 * Gets an empty response that can be initialized by a stream.
 * <br/>
 * This method has to be used to build response items about a batch request.
 *
 * @param <V> ODataResponse type.
 * @return empty OData response instance.
 */
@SuppressWarnings("unchecked")
public <V extends ODataResponse> V getResponseTemplate() {
  for (Class<?> clazz : this.getClass().getDeclaredClasses()) {
    if (ODataResponse.class.isAssignableFrom(clazz)) {
      try {
        final Constructor<?> constructor = clazz.getDeclaredConstructor(
            this.getClass(), ODataClient.class, HttpClient.class, HttpResponse.class);
        constructor.setAccessible(true);
        return (V) constructor.newInstance(this, odataClient, httpClient, null);
      } catch (Exception e) {
        LOG.error("Error retrieving response class template instance", e);
      }
    }
  }

  throw new IllegalStateException("No response class template has been found");
}
 
源代码15 项目: pacbot   文件: ApiService.java
/**
 * 
 * @param url
 * @param requestBody
 * @param headers
 * @return
 */
public String doHttpPost(final String url, final String requestBody, final Map<String, String> headers)
{
     try {
		 HttpClient client = HttpClientBuilder.create().build();
	     HttpPost httppost = new HttpPost(url);
		 for (Map.Entry<String, String> entry : headers.entrySet()) {
			 httppost.addHeader(entry.getKey(), entry.getValue());
		 }
	     StringEntity jsonEntity = new StringEntity(requestBody);
	     httppost.setEntity(jsonEntity);
	     HttpResponse httpresponse = client.execute(httppost);
		 return EntityUtils.toString(httpresponse.getEntity());
	} catch (org.apache.http.ParseException parseException) {
		log.error("ParseException : "+parseException.getMessage());
	} catch (IOException ioException) {
		log.error("IOException : "+ioException.getMessage());
	}
	return null;
}
 
源代码16 项目: JavaRushTasks   文件: Solution.java
public void sendPost(String url, String urlParameters) throws Exception {
    HttpClient client = getHttpClient();
    HttpPost request = new HttpPost(url);
    request.addHeader("User-Agent", "Mozilla/5.0");

    List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
    String[] s = urlParameters.split("&");
    for (int i = 0; i < s.length; i++) {
        String g = s[i];
        valuePairs.add(new BasicNameValuePair(g.substring(0,g.indexOf("=")), g.substring(g.indexOf("=")+1)));
    }

    request.setEntity(new UrlEncodedFormEntity(valuePairs));
    HttpResponse response = client.execute(request);
    System.out.println("Response Code: " + response.getStatusLine().getStatusCode());

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String responseLine;
    while ((responseLine = bufferedReader.readLine()) != null) {
        result.append(responseLine);
    }

    System.out.println("Response: " + result.toString());
}
 
源代码17 项目: Onosendai   文件: SuccessWhale.java
public TweetList getFeed (final SuccessWhaleFeed feed, final String sinceId, final Collection<Meta> extraMetas) throws SuccessWhaleException {
		return authenticated(new SwCall<TweetList>() {
			private String url;

			@Override
			public TweetList invoke (final HttpClient client) throws IOException {
				this.url = makeAuthedUrl(API_FEED, "&sources=", URLEncoder.encode(feed.getSources(), "UTF-8"));

				// FIXME disabling this until SW finds a way to accept it on mixed feeds [issue 89].
//				if (sinceId != null) this.url += "&since_id=" + sinceId;

				final HttpGet req = new HttpGet(this.url);
				AndroidHttpClient.modifyRequestToAcceptGzipResponse(req);
				return client.execute(req, new FeedHandler(getAccount(), extraMetas));
			}

			@Override
			public String describeFailure (final Exception e) {
				return "Failed to fetch feed '" + feed + "' from '" + this.url + "': " + e.toString();
			}
		});
	}
 
源代码18 项目: find   文件: HodConfiguration.java
@Bean
public HodServiceConfig.Builder<EntityType.Combined, TokenType.Simple> hodServiceConfigBuilder(
        final HttpClient httpClient,
        final ObjectMapper objectMapper,
        final ConfigService<HodFindConfig> configService
) {
    final URL endpoint = configService.getConfig().getHod().getEndpointUrl();

    return new HodServiceConfig.Builder<EntityType.Combined, TokenType.Simple>(endpoint.toString())
            .setHttpClient(httpClient)
            .setObjectMapper(objectMapper)
            .setTokenRepository(tokenRepository);
}
 
@Test(expected = GithubAuthenticationException.class)
public void shouldNotAuthenticateIfUserNotInOrg() throws Exception {
    HttpClient mockClient = fullyFunctionalMockClient();
    config.setGithubOrg("OTHER-ORG");
    GithubApiClient clientToTest = new GithubApiClient(mockClient, config);
    clientToTest.authz("demo-user", "DUMMY".toCharArray());
}
 
源代码20 项目: dx-java   文件: InsightDataManager.java
/**
 * Create a HttpClient
 * 
 * @return a HttpClient
 */
private HttpClient createHttpClient() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(DEFAULT_MAX_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MercadoPago.SDK.getMaxConnections());
    connectionManager.setValidateAfterInactivity(VALIDATE_INACTIVITY_INTERVAL_MS);
    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(MercadoPago.SDK.getRetries(),
            false);

    HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
            .setKeepAliveStrategy(new KeepAliveStrategy()).setRetryHandler(retryHandler).disableCookieManagement()
            .disableRedirectHandling();

    return httpClientBuilder.build();
}
 
源代码21 项目: OnionHarvester   文件: OnionGrabber.java
public Object[] getNewOnions() {
    Vector<Object> out = new Vector<>();

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(URLGenerate);

    // add request header
    request.addHeader("User-Agent", "OnionHarvester - Java Client");
    try {
        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() != 200) {
            out.add(false);
            return out.toArray();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        String temp = result.toString();
        jobj = new JSONObject(temp);
        jobj.getJSONArray("ports").iterator().forEachRemaining(o -> {
            getPorts().add(Integer.valueOf((String) o));
        });
        out.add(true);
        out.add(jobj.getString("start"));
        out.add(jobj.getString("end"));
        out.add(jobj.getString("id"));
    } catch (Exception ex) {
        out.add(false);
    } finally {
        return out.toArray();
    }
}
 
源代码22 项目: atlas   文件: HttpClientUtils.java
/**
 * 简单的获取http get结果
 * @param url
 * @return
 * @throws IOException
 */
public static String getUrl(String url) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    String html = EntityUtils.toString(entity, "UTF-8");
    httpget.releaseConnection();
    return html;
}
 
源代码23 项目: forge-api-java-client   文件: OAuth2ThreeLegged.java
private String execute(HttpRequestBase request) throws ClientProtocolException, IOException, ApiException {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse response = httpClient.execute(request);

    HttpEntity entity = response.getEntity();
    String body = EntityUtils.toString(entity);

    int status = response.getStatusLine().getStatusCode();
    if (status != 200) {
        throw new ApiException(status, body);
    }

    return body;
}
 
源代码24 项目: InflatableDonkey   文件: EscrowOperationsRecords.java
public static NSDictionary records(HttpClient httpClient, EscrowProxyRequestFactory requests) throws IOException {
    /* 
    EscrowService SRP-6a exchanges: GETRECORDS
     */
    HttpUriRequest recordsRequest = requests.getRecords();
    NSDictionary dictionary = httpClient.execute(recordsRequest, RESPONSE_HANDLER);
    logger.debug("-- records() - GETRECORDS: {}", dictionary.toXMLPropertyList());
    return dictionary;
}
 
源代码25 项目: WavesJ   文件: Node.java
private HttpClient createDefaultClient() {
    return HttpClients.custom().setDefaultRequestConfig(
            RequestConfig.custom()
                    .setSocketTimeout(5000)
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000)
                    .setCookieSpec(CookieSpecs.STANDARD)
                    .build())
            .build();
}
 
源代码26 项目: Patterdale   文件: PatterdaleFunctionalTest.java
@Test
public void readyPageReturns200andOK() throws Exception {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse response = httpClient.execute(new HttpGet("http://localhost:7001/ready"));

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    assertThat(responseBody(response)).contains("OK");
}
 
源代码27 项目: rainbow   文件: HttpUtil.java
public static Object HttpGet(String aUrl) {
    String res = "";
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(aUrl);// init
    try {
        HttpResponse httpResponse = httpClient.execute(httpGet);// accept msg
        HttpEntity entity = httpResponse.getEntity();// get result from msg
        if (entity != null) {
            res = EntityUtils.toString(entity, "UTF-8");// change to string type
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return res;
}
 
源代码28 项目: customer-review-crawler   文件: GetASINbyNode.java
/**
 * Returns a webpage's html code
 * @param weburl The URL to read webpage from
 * @return return a string that contains the HTML code of the webpage
 * @throws IOException
 */
public String readWebPage(String weburl) throws IOException{
	HttpClient httpclient = new DefaultHttpClient();
	//HttpProtocolParams.setUserAgent(httpclient.getParams(), "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
	HttpGet httpget = new HttpGet(weburl); 
	ResponseHandler<String> responseHandler = new BasicResponseHandler();    
	String responseBody = httpclient.execute(httpget, responseHandler);
	// responseBody now contains the contents of the page
	// System.out.println(responseBody);
	httpclient.getConnectionManager().shutdown();
	return responseBody;
}
 
源代码29 项目: AIDR   文件: PersisterService.java
public String sendPost(String data, String url) {
    int responseCode = -1;
    HttpClient httpClient = new DefaultHttpClient();
    String str = "";
    try {
        HttpPost request = new HttpPost(url);
        StringEntity params =new StringEntity(data, "UTF-8");
        params.setContentType("application/json");
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        responseCode = response.getStatusLine().getStatusCode();

        if ( responseCode == 200 || responseCode == 204) {
            if(response.getEntity()!=null){
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));

                String output;
                while ((output = br.readLine()) != null) {
                	str = str + output;
                }
            }
        }
        else{
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

    }catch (Exception ex) {
    	return null;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return str;
}
 
源代码30 项目: nexus-public   文件: OrientNpmProxyFacet.java
/**
 * Execute http client request.
 */
protected HttpResponse execute(final Context context, final HttpClient client, final HttpRequestBase request)
    throws IOException
{
  String bearerToken = getRepository().facet(HttpClientFacet.class).getBearerToken();
  if (StringUtils.isNotBlank(bearerToken)) {
    request.setHeader("Authorization", "Bearer " + bearerToken);
  }
  return super.execute(context, client, request);
}
 
 类所在包
 同包方法