private static HttpClient getHttpClient() { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init( null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }, new SecureRandom()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build(); return httpClient; } catch (Exception e) { e.printStackTrace(); return HttpClientBuilder.create().build(); } }
@Override public void activateBrowserfeatures(final Upload upload) throws UnirestException { // Create a local instance of cookie store // Populate cookies if needed final CookieStore cookieStore = new BasicCookieStore(); for (final PersistentCookieStore.SerializableCookie serializableCookie : upload.getAccount().getSerializeableCookies()) { final BasicClientCookie cookie = new BasicClientCookie( serializableCookie.getCookie().getName(), serializableCookie.getCookie().getValue()); cookie.setDomain(serializableCookie.getCookie().getDomain()); cookieStore.addCookie(cookie); } final HttpClient client = HttpClientBuilder.create().useSystemProperties().setDefaultCookieStore(cookieStore).build(); Unirest.setHttpClient(client); final HttpResponse<String> response = Unirest.get(String.format(VIDEO_EDIT_URL, upload.getVideoid())).asString(); changeMetadata(response.getBody(), upload); final RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(600000).build(); Unirest.setHttpClient(HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).build()); }
private HttpClient getHttpClient() { HttpClient client = null; if (proxyHost != null) { client = HttpClientBuilder.create() .setRoutePlanner(new DefaultProxyRoutePlanner(proxyHost)) .build(); } else { client = HttpClientBuilder.create().build(); } return client; }
// String endpoint="http://20.0.1.179"; // String p="9097"; public void getSellerInventoryPricingForPDP(Message message, ReadConfig rc) { boolean isWorking = false; String url = "/service/ipms/getSellerInventoryPricingForPDP"; String json = "{\"orderedSUPCList\":[\"SDL994240556\"],\"zone\":\"1\",\"responseProtocol\":\"PROTOCOL_JSON\",\"requestProtocol\":\"PROTOCOL_JSON\"}"; String endpoint = rc.getPropValues("ipmsIP"); String p = rc.getPropValues("ipmsPort"); String finalUrl = endpoint + ":" + p + url; HttpPost request = new HttpPost(finalUrl); StringEntity entity = null; try { entity = new StringEntity(json); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } entity.setContentType("application/json"); request.setEntity(entity); HttpResponse response = null; HttpClient httpclient = HttpClientBuilder.create().build(); try { response = httpclient.execute(request); } catch (IOException e) { e.printStackTrace(); } try { isWorking = response.toString().contains("200"); } catch (Exception e) { System.out.println("getSellerInventoryPricingForPDP"); } if (!isWorking) message .getErrorMessageList() .add("Error: The IPMS is down now on IP :" + endpoint + " and port " + p); else System.out.println("IPMS IS UP"); }
/** HttpClient 4.3简单入门---HttpPost */ @Test public void test02() { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); HttpPost httpPost = new HttpPost(HTTPPOSTTESTURL); // httpPost.setConfig(); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 创建参数列表 formParams.add(new BasicNameValuePair("type", "all")); formParams.add(new BasicNameValuePair("query", "httpClient")); formParams.add(new BasicNameValuePair("sort", "")); UrlEncodedFormEntity entity; try { entity = new UrlEncodedFormEntity(formParams, "UTF-8"); httpPost.setEntity(entity); HttpResponse httpResponse = closeableHttpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { logger.info("response:{}", EntityUtils.toString(httpEntity, "UTF-8")); } closeableHttpClient.close(); // 释放资源 } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public TestHttpClient(String uri, String stringParams) throws UnsupportedEncodingException { httpClient = HttpClientBuilder.create().build(); postRequest = new HttpPost(uri); StringEntity params = new StringEntity(stringParams); postRequest.addHeader("content-type", "application/json"); postRequest.setEntity(params); }
/** * Constructor for using an API key * * @param apiKey SendGrid api key */ public SendGrid(String apiKey) { this.password = apiKey; this.username = null; this.url = "https://api.sendgrid.com"; this.endpoint = "/api/mail.send.json"; this.client = HttpClientBuilder.create().setUserAgent(USER_AGENT).build(); }
/*.................................................................................................................*/ public HttpClient getHttpClient() { // from http://www.artima.com/forums/flat.jsp?forum=121&thread=357685 CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); provider.setCredentials(AuthScope.ANY, credentials); return HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); }
private static String queryBattle(String url) { StringBuilder builder = new StringBuilder(); HttpClient client = HttpClientBuilder.create().build(); try { HttpGet httpGet = new HttpGet(URIUtil.encodeQuery(url)); HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content, "UTF-8")); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { LOGGER.error("Failed to download file"); return null; } } catch (IOException e) { LOGGER.error(e); } return builder.toString(); }
public static void main(String[] args) throws ClientProtocolException, IOException { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { // HttpClient httpClient = getTestHttpClient(); // HttpHost proxy = new HttpHost("127.0.0.1", 8888); // httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, // proxy); String apiKey = args[0]; String latitude = "46.947922"; String longitude = "7.444608"; String urlTemplate = "https://api.forecast.io/forecast/%s/%s,%s"; String url = String.format(urlTemplate, apiKey, latitude, longitude); System.out.println(url); HttpGet httpget = new HttpGet(url); try (CloseableHttpResponse response = httpClient.execute(httpget)) { System.out.println(response.getFirstHeader("Content-Encoding")); HeaderIterator it = response.headerIterator(); while (it.hasNext()) { Object header = it.next(); System.out.println(header); } HttpEntity entity = response.getEntity(); String jsonData = EntityUtils.toString(entity, StandardCharsets.UTF_8); System.out.println(jsonData); } } }
public static void main(String[] args) throws Exception { HttpGet get = new HttpGet("https://localhost/docs/index.html"); HttpClientBuilder client = HttpClientBuilder.create(); ServerConfig config = new ServerConfig(new Properties()); config.setParam("https.keyStoreFile", "test.keystore"); config.setParam("https.keyPassword", "nopassword"); config.setParam("https.keyStoreType", "JKS"); config.setParam("https.protocol", "SSLv3"); // SSLContextCreator ssl = new SSLContextCreator(config); // SSLContext ctx = ssl.getSSLContext(); // ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( // client.getConnectionManager().getSchemeRegistry(), // ProxySelector.getDefault()); // client.setRoutePlanner(routePlanner); // SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); // socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // DefaultSchemePortResolver sch = new DefaultSchemePortResolver(); // sch.("https", 443, socketFactory); // CloseableHttpClient c = client.build(); // getConnectionManager().getSchemeRegistry().register(sch); HttpResponse response = client.build().execute(get); System.out.println(response.getStatusLine().getStatusCode()); }
@Override public String getChannels(String serverUrl, boolean premium) throws ClientProtocolException, UnsupportedEncodingException, IOException { String playLIst = null; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // CloseableHttpClient httpClient = HttpClients.custom().setRoutePlanner(routePlanner).build(); HttpResponse login = httpClient.execute(getVideoStarLogin()); EntityUtils.consume(login.getEntity()); if (login.getStatusLine().getStatusCode() == 302) { HttpResponse getChannel = httpClient.execute(getChannelsRequest(login)); if (getChannel.getStatusLine().getStatusCode() == 200) { VideoStarChannelRequest channels = jsonService.parseVideoStarChannels(EntityUtils.toString(getChannel.getEntity())); if (channels != null && channels.getStatus().equals("ok")) { return prepareChannelList(channels, serverUrl, premium); // return channelsString; } else if (channels != null && channels.getStatus().equals("error")) { // TODO } else { // TODO } } } return playLIst; }
/** * proxy query log for the specified task. * * @param task the specified task */ private void listLogs() { // PROXY_URL = "http://%s:%s/logview?%s=%s"; String url = String.format( PROXY_URL, host, port, HttpserverUtils.HTTPSERVER_LOGVIEW_PARAM_CMD, HttpserverUtils.HTTPSERVER_LOGVIEW_PARAM_CMD_LIST); try { // 1. proxy call the task host log view service HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); HttpResponse response = client.execute(post); // 2. check the request is success, then read the log if (response.getStatusLine().getStatusCode() == 200) { String data = EntityUtils.toString(response.getEntity()); parseString(data); } else { String data = EntityUtils.toString(response.getEntity()); summary = ("Failed to get files\n" + data); } } catch (Exception e) { summary = ("Failed to get files\n" + e.getMessage()); LOG.error(e.getCause(), e); } }
@BeforeClass public static void beforeClass() throws Exception { ourPort = PortUtil.findFreePort(); ourServer = new Server(ourPort); DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider(); ServletHandler proxyHandler = new ServletHandler(); ourServlet = new RestfulServer(); ourServlet.getFhirContext().setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator()); ourServlet.setPagingProvider(new FifoMemoryPagingProvider(10).setDefaultPageSize(10)); ourServlet.setResourceProviders(patientProvider, new DummyObservationResourceProvider()); ServletHolder servletHolder = new ServletHolder(ourServlet); proxyHandler.addServletWithMapping(servletHolder, "/*"); ourServer.setHandler(proxyHandler); ourServer.start(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setConnectionManager(connectionManager); ourClient = builder.build(); ourDefaultAddressStrategy = ourServlet.getServerAddressStrategy(); }
public void getTPBShows() { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { HttpGet httpGet = new HttpGet(pageURL); httpGet.addHeader( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"); response = httpClient.execute(httpGet); HttpEntity httpEntity = response.getEntity(); Header contentType = response.getFirstHeader("Content-Type"); String[] contentArray = contentType.getValue().split(";"); String charset = "UTF-8"; // String mimeType = contentArray[0].trim(); if (contentArray.length > 1 && contentArray[1].contains("=")) { charset = contentArray[1].trim().split("=")[1]; } Document pageDoc = Jsoup.parse(httpEntity.getContent(), charset, httpGet.getURI().getPath()); Element results = pageDoc.getElementById("searchResult"); response.close(); Elements rawShowObjects = results.select("td.vertTh+td"); TPBToTvShowEpisode makeShows = new TPBToTvShowEpisode(); List<TvShowEpisode> theShows = makeShows.makeTSEBeans(rawShowObjects); DBActions.insertTvEpisodes(theShows, pageURL); } catch (MalformedURLException MURLe) { // Utilities.sendExceptionEmail(MURLe.getMessage()); MURLe.printStackTrace(); } catch (Exception e) { // Utilities.sendExceptionEmail(e.getMessage()); e.printStackTrace(); } }
public String getExstention() { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { HttpGet httpGet = new HttpGet("http://thepiratebay.org"); httpGet.addHeader( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"); response = httpClient.execute(httpGet); Header[] cookieJar = response.getHeaders("set-cookie"); if (response.getStatusLine().getStatusCode() == 200 && cookieJar.length > 0) { for (int i = 0; i < cookieJar.length; i++) { String[] cookies = response.getHeaders("set-cookie")[i].getValue().split(";"); for (int c = 0; c < cookies.length; c++) { if (cookies[c].contains("domain=")) { return cookies[c].substring(cookies[c].indexOf('=') + 2); } } } } else { SendMailTLS sendMail = new SendMailTLS(); sendMail.sendEmail("FAILD TO OBTAIN WEB EXTENTION!", response.toString()); return "FAIL"; } response.close(); } catch (Exception e) { Utilities.sendExceptionEmail(e.getMessage()); return e.getMessage(); } return ""; }
@BeforeClass public static void beforeClass() throws Exception { ourPort = PortUtil.findFreePort(); ourServer = new Server(ourPort); PatientProvider patientProvider = new PatientProvider(); ourReportProvider = new DiagnosticReportProvider(); ServletHandler proxyHandler = new ServletHandler(); RestfulServer servlet = new RestfulServer(ourCtx); servlet.setResourceProviders( patientProvider, ourReportProvider, new ObservationProvider(), new OrganizationResourceProvider()); ServletHolder servletHolder = new ServletHolder(servlet); proxyHandler.addServletWithMapping(servletHolder, "/*"); ourServer.setHandler(proxyHandler); ourServer.start(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setConnectionManager(connectionManager); ourClient = builder.build(); }
/** * Pulls a page and attempts to discover a feed for it via link[rel='alternate']. * * @param url The URL of the page to try and discover the feed for. * @return The feedsource if matched or created, may be null. * @throws ClientProtocolException If the page could not be pulled. * @throws IOException If the page could not be pulled. * @throws DataOperationException If a query could not be executed. */ public FeedSource discover(final String url) throws ClientProtocolException, IOException, DataOperationException { log.fine("Discovering feed for " + url); try (final CloseableHttpClient client = HttpClientBuilder.create().build()) { final HttpGet get = new HttpGet(url); try (final CloseableHttpResponse response = client.execute(get)) { final String html = EntityUtils.toString(response.getEntity()); final Document doc = Jsoup.parse(html); final Elements alternateLinks = doc.select("link"); for (final Element alternateLink : alternateLinks) { if ("alternate".equals(alternateLink.attr("rel"))) { if ("application/rss+xml".equals(alternateLink.attr("type"))) { log.fine("Found rss link " + alternateLink.attr("href")); final String rss = alternateLink.attr("href"); return this.feedSourceManager.findOrCreateByFeedUrl(rss); } log.fine("Found alternate link " + alternateLink.html()); } else { log.fine("Found link " + alternateLink.html()); } } } } return null; }
public static void createCreative(Creative creative) throws Exception { int status = 0; String jsonString = null; CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost("https://rest.emaildirect.com/v1/Creatives?ApiKey=apikey"); List<NameValuePair> params = creative.getParams(); post.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); try { jsonString = rd.lines().collect(Collectors.joining()).toString(); System.out.println("JSON ->" + jsonString); } finally { rd.close(); } } JSONObject jObj = new JSONObject(jsonString); if (status == 201) { creative.setCreativeID(jObj.getString("CreativeID")); creative.setCreativeTimestamp(jObj.getString("Created")); dbUpdate(creative); } }
public void testMojoExecution() throws Exception { assertNotNull(mojo); mojo.execute(); HttpClient client = HttpClientBuilder.create().build(); HttpGet get = new HttpGet("http://localhost:" + elasticsearchNode.getHttpPort()); final int connectionTimeout = 500; // millis RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(connectionTimeout) .setConnectTimeout(connectionTimeout) .setSocketTimeout(connectionTimeout) .build(); get.setConfig(requestConfig); try { client.execute(get); fail("The ES cluster should have been down by now"); } catch (HttpHostConnectException | ConnectTimeoutException expected) { } assertTrue(elasticsearchNode.isClosed()); }
public static String download(String urlStr) { HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(urlStr); // add request header final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0"; request.addHeader("User-Agent", USER_AGENT); HttpResponse response; try { response = client.execute(request); byte[] rawresponse = EntityUtils.toByteArray(response.getEntity()); String encoding = HTML_Downloader.detectEncoding(new String(rawresponse)); if (encoding != null) { return new String(rawresponse, encoding); } else { return new String(rawresponse, "utf8"); } } catch (IOException e) { e.printStackTrace(); } return ""; }
/** * Key store 类型HttpClient * * @param keystore keystore * @param keyPassword keyPassword * @param supportedProtocols supportedProtocols * @param timeout timeout * @param retryExecutionCount retryExecutionCount * @return CloseableHttpClient */ public static CloseableHttpClient createKeyMaterialHttpClient( KeyStore keystore, String keyPassword, String[] supportedProtocols, int timeout, int retryExecutionCount) { try { SSLContext sslContext = SSLContexts.custom() .useSSL() .loadKeyMaterial(keystore, keyPassword.toCharArray()) .build(); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory( sslContext, supportedProtocols, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build(); return HttpClientBuilder.create() .setDefaultSocketConfig(socketConfig) .setSSLSocketFactory(sf) .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount)) .build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } return null; }
public static void refresh() { // Load timeouts Object connectionTimeout = Options.getOption(Option.CONNECTION_TIMEOUT); if (connectionTimeout == null) connectionTimeout = CONNECTION_TIMEOUT; Object socketTimeout = Options.getOption(Option.SOCKET_TIMEOUT); if (socketTimeout == null) socketTimeout = SOCKET_TIMEOUT; // Create common default configuration RequestConfig clientConfig = RequestConfig.custom() .setConnectTimeout(((Long) connectionTimeout).intValue()) .setSocketTimeout(((Long) socketTimeout).intValue()) .build(); // Create clients setOption( Option.HTTPCLIENT, HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).build()); CloseableHttpAsyncClient asyncClient = HttpAsyncClientBuilder.create().setDefaultRequestConfig(clientConfig).build(); asyncClient.start(); setOption(Option.ASYNCHTTPCLIENT, asyncClient); }
public String getPageContent(String uri) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); HttpClient httpClient = httpClientBuilder.build(); HttpUriRequest httpReq = new HttpGet(uri); HttpResponse httpResp = null; HttpEntity httpEntity = null; try { httpResp = httpClient.execute(httpReq); httpEntity = httpResp.getEntity(); if (httpEntity != null) { InputStream is = httpEntity.getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); writer.close(); is.close(); return writer.toString(); } } catch (IOException e) { logger.error("获取网页内容时,发生异常,具体为:{}", e); return StringUtils.EMPTY; } finally { httpReq.abort(); try { EntityUtils.consume(httpEntity); } catch (Exception e2) { } } return StringUtils.EMPTY; }
/** * @param maxTotal maxTotal * @param maxPerRoute maxPerRoute * @param timeout timeout * @param retryExecutionCount retryExecutionCount * @return */ public static CloseableHttpClient createHttpClient( int maxTotal, int maxPerRoute, int timeout, int retryExecutionCount) { try { SSLContext sslContext = SSLContexts.custom().useSSL().build(); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); poolingHttpClientConnectionManager.setMaxTotal(maxTotal); poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPerRoute); SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build(); poolingHttpClientConnectionManager.setDefaultSocketConfig(socketConfig); return HttpClientBuilder.create() .setConnectionManager(poolingHttpClientConnectionManager) .setSSLSocketFactory(sf) .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount)) .build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
public static void headerRequest() { try { HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("http://mkyong.com"); HttpResponse response = client.execute(request); System.out.println("Printing Response Header...\n"); Header[] headers = response.getAllHeaders(); for (Header header : headers) { System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue()); } System.out.println("\nGet Response Header By Key ...\n"); String server = response.getFirstHeader("Server").getValue(); if (server == null) { System.out.println("Key 'Server' is not found!"); } else { System.out.println("Server - " + server); } System.out.println("\n Done"); } catch (Exception e) { e.printStackTrace(); } }
public static String sendToRockBlockHttp( String destImei, String username, String password, byte[] data) throws HttpException, IOException { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost("https://secure.rock7mobile.com/rockblock/MT"); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("imei", destImei)); urlParameters.add(new BasicNameValuePair("username", username)); urlParameters.add(new BasicNameValuePair("password", password)); urlParameters.add(new BasicNameValuePair("data", ByteUtil.encodeToHex(data))); post.setEntity(new UrlEncodedFormEntity(urlParameters)); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } try { client.close(); } catch (Exception e) { e.printStackTrace(); } return result.toString(); }
/** Unit tests for {@link Builder}. */ public class LBHttpSolrClientBuilderTest extends LuceneTestCase { private static final String ANY_BASE_SOLR_URL = "ANY_BASE_SOLR_URL"; private static final HttpClient ANY_HTTP_CLIENT = HttpClientBuilder.create().build(); private static final ResponseParser ANY_RESPONSE_PARSER = new NoOpResponseParser(); @Test public void providesHttpClientToClient() { try (LBHttpSolrClient createdClient = new Builder().withBaseSolrUrl(ANY_BASE_SOLR_URL).withHttpClient(ANY_HTTP_CLIENT).build()) { assertTrue(createdClient.getHttpClient().equals(ANY_HTTP_CLIENT)); } } @Test public void providesResponseParserToClient() { try (LBHttpSolrClient createdClient = new Builder() .withBaseSolrUrl(ANY_BASE_SOLR_URL) .withResponseParser(ANY_RESPONSE_PARSER) .build()) { assertTrue(createdClient.getParser().equals(ANY_RESPONSE_PARSER)); } } @Test public void testDefaultsToBinaryResponseParserWhenNoneProvided() { try (LBHttpSolrClient createdClient = new Builder().withBaseSolrUrl(ANY_BASE_SOLR_URL).build()) { final ResponseParser usedParser = createdClient.getParser(); assertTrue(usedParser instanceof BinaryResponseParser); } } }
/** HttpClient 4.3 简单入门---HttpGet */ @Test public void test01() { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // 创建httpClientBuilder CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); // 创建httpClient HttpGet httpGet = new HttpGet(HTTPGETTESTURL); logger.info("httpGet.getRequestLine():{}", httpGet.getRequestLine()); try { HttpResponse httpResponse = closeableHttpClient.execute(httpGet); // 执行get请求 HttpEntity httpEntity = httpResponse.getEntity(); // 获取响应消息实体 logger.info("响应状态:{}", httpResponse.getStatusLine()); if (httpEntity != null) { logger.info("contentEncoding:{}", httpEntity.getContentEncoding()); logger.info("response content:{}", EntityUtils.toString(httpEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { closeableHttpClient.close(); // 关闭流并释放资源 } catch (IOException e) { e.printStackTrace(); } } }
public void GetOauthToken() { HttpClient httpclient = HttpClientBuilder.create().build(); // Assemble the login request URL String loginURL = LOGINURL + GRANTSERVICE + "&client_id=" + CLIENTID + "&client_secret=" + CLIENTSECRET + "&username="******"&password="******"Error authenticating to Force.com: " + statusCode); // Error is in EntityUtils.toString(response.getEntity()) return; } String getResult = null; try { getResult = EntityUtils.toString(response.getEntity()); } catch (IOException ioException) { ioException.printStackTrace(); } JSONObject jsonObject = null; try { jsonObject = (JSONObject) new JSONTokener(getResult).nextValue(); loginAccessToken = jsonObject.getString("access_token"); loginInstanceUrl = jsonObject.getString("instance_url"); } catch (JSONException jsonException) { jsonException.printStackTrace(); } System.out.println(response.getStatusLine()); System.out.println("Successful login"); System.out.println(" instance URL: " + loginInstanceUrl); System.out.println(" access token/session ID: " + loginAccessToken); // release connection httpPost.releaseConnection(); }