Java Code Examples for org.apache.http.client.HttpClient

The following examples show how to use org.apache.http.client.HttpClient. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: keycloak   Source File: ProductDatabaseClient.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 2
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;
}
 
Example 3
Source Project: carbon-apimgt   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source Project: keycloak   Source File: RegistrationRecaptcha.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source Project: coolreader   Source File: AppUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 获取网址内容
 * @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();
}
 
Example 6
Source Project: IGUANA   Source File: UPDATEWorker.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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);
	}

}
 
Example 7
@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"));
  }
}
 
Example 8
Source Project: NLIWOD   Source File: RunProducer.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 "";
	}
	
	
}
 
Example 9
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;
	
}
 
Example 10
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);
}
 
Example 11
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;
}
 
Example 12
Source Project: AppServiceRestFul   Source File: Util.java    License: GNU General Public License v3.0 6 votes vote down vote up
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(); 
   } 
}
 
Example 13
Source Project: product-ei   Source File: SPARQLServiceTestCase.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 14
Source Project: olingo-odata4   Source File: AbstractODataRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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");
}
 
Example 15
Source Project: pacbot   Source File: ApiService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @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;
}
 
Example 16
Source Project: JavaRushTasks   Source File: Solution.java    License: MIT License 6 votes vote down vote up
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());
}
 
Example 17
Source Project: Onosendai   Source File: SuccessWhale.java    License: Apache License 2.0 6 votes vote down vote up
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();
			}
		});
	}
 
Example 18
Source Project: find   Source File: HodConfiguration.java    License: MIT License 5 votes vote down vote up
@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);
}
 
Example 19
Source Project: nexus3-github-oauth-plugin   Source File: GithubApiClientTest.java    License: MIT License 5 votes vote down vote up
@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());
}
 
Example 20
Source Project: dx-java   Source File: InsightDataManager.java    License: MIT License 5 votes vote down vote up
/**
 * 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();
}
 
Example 21
Source Project: OnionHarvester   Source File: OnionGrabber.java    License: GNU General Public License v3.0 5 votes vote down vote up
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();
    }
}
 
Example 22
Source Project: atlas   Source File: HttpClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 简单的获取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;
}
 
Example 23
Source Project: forge-api-java-client   Source File: OAuth2ThreeLegged.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 24
Source Project: InflatableDonkey   Source File: EscrowOperationsRecords.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example 25
Source Project: WavesJ   Source File: Node.java    License: MIT License 5 votes vote down vote up
private HttpClient createDefaultClient() {
    return HttpClients.custom().setDefaultRequestConfig(
            RequestConfig.custom()
                    .setSocketTimeout(5000)
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000)
                    .setCookieSpec(CookieSpecs.STANDARD)
                    .build())
            .build();
}
 
Example 26
Source Project: Patterdale   Source File: PatterdaleFunctionalTest.java    License: Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 27
Source Project: rainbow   Source File: HttpUtil.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 28
Source Project: customer-review-crawler   Source File: GetASINbyNode.java    License: The Unlicense 5 votes vote down vote up
/**
 * 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;
}
 
Example 29
Source Project: AIDR   Source File: PersisterService.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 30
Source Project: nexus-public   Source File: OrientNpmProxyFacet.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
}