點擊進入 個人爲知筆記連接(帶格式)
html
1 CloseableHttpClient httpclient = HttpClients.createDefault(); 2 HttpGet httpget = new HttpGet("http://localhost/"); 3 CloseableHttpResponse response = httpclient.execute(httpget); 4 try { 5 <...> 6 } finally { 7 response.close(); 8 }
1 URI uri = new URIBuilder() 2 .setScheme("http") 3 .setHost("www.google.com") 4 .setPath("/search") 5 .setParameter("q", "httpclient") 6 .setParameter("btnG", "Google Search") 7 .setParameter("aq", "f") 8 .setParameter("oq", "") 9 .build(); 10 HttpGet httpget = new HttpGet(uri); 11 System.out.println(httpget.getURI());
1 HttpResponse response = new asicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); 2 System.out.println(response.getProtocolVersion()); 3 System.out.println(response.getStatusLine().getStatusCode()); 4 System.out.println(response.getStatusLine().getReasonPhrase()); 5 System.out.println(response.getStatusLine().toString());
1 CloseableHttpClient httpclient = HttpClients.createDefault(); 2 HttpGet httpget = new HttpGet("http://localhost/"); 3 CloseableHttpResponse response = httpclient.execute(httpget); 4 try { 5 HttpEntity entity = response.getEntity(); 6 if (entity != null) { 7 InputStream instream = entity.getContent(); 8 try { 9 // do something useful 10 } finally { 11 instream.close(); 12 } 13 } 14 } finally { 15 response.close(); 16 }
1 CloseableHttpClient httpclient = HttpClients.createDefault(); 2 HttpGet httpget = new HttpGet("http://localhost/"); 3 CloseableHttpResponse response = httpclient.execute(httpget); 4 try { 5 HttpEntity entity = response.getEntity(); 6 if (entity != null) { 7 InputStream instream = entity.getContent(); 8 int byteOne = instream.read(); 9 int byteTwo = instream.read(); 10 // Do not need the rest 不須要剩下的部分 11 } 12 } finally { 13 response.close(); 14 }
1 CloseableHttpClient httpclient = HttpClients.createDefault(); 2 HttpGet httpget = new HttpGet("http://localhost/"); 3 CloseableHttpResponse response = httpclient.execute(httpget); 4 try { 5 HttpEntity entity = response.getEntity(); 6 if (entity != null) { 7 long len = entity.getContentLength(); 8 if (len != -1 && len < 2048) { 9 System.out.println(EntityUtils.toString(entity)); 10 } else { 11 // Stream content out 12 } 13 } 14 } finally { 15 response.close(); 16 }
1 CloseableHttpResponse response = <...> 2 HttpEntity entity = response.getEntity(); 3 if (entity != null) { 4 entity = new BufferedHttpEntity(entity); 5 }
1 File file = new File("somefile.txt"); 2 FileEntity entity = new FileEntity(file, 3 ContentType.create("text/plain", "UTF-8")); 4 HttpPost httppost = new HttpPost("http://localhost/action.do"); 5 httppost.setEntity(entity);
1 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); 2 formparams.add(new BasicNameValuePair("param1", "value1")); 3 formparams.add(new BasicNameValuePair("param2", "value2")); 4 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); 5 HttpPost httppost = new HttpPost("http://localhost/handler.do"); 6 httppost.setEntity(entity);
1 StringEntity entity = new StringEntity("important message", 2 ContentType.create("plain/text", Consts.UTF_8)); 3 entity.setChunked(true); 4 HttpPost httppost = new HttpPost("http://localhost/acrtion.do"); 5 httppost.setEntity(entity);
1 CloseableHttpClient httpclient = HttpClients.createDefault(); 2 HttpGet httpget = new HttpGet("http://localhost/json"); 3 ResponseHandler<MyJsonObject> rh = new ResponseHandler<MyJsonObject>() { 4 @Override 5 public JsonObject handleResponse(final HttpResponse response) throws IOException { 6 StatusLine statusLine = response.getStatusLine(); 7 HttpEntity entity = response.getEntity(); 8 if (statusLine.getStatusCode() >= 300) { 9 throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); 10 } 11 if (entity == null) { 12 throw new ClientProtocolException("Response contains no content"); 13 } 14 Gson gson = new GsonBuilder().create(); 15 ContentType contentType = ContentType.getOrDefault(entity); 16 Charset charset = contentType.getCharset(); 17 Reader reader = new InputStreamReader(entity.getContent(), charset); 18 return gson.fromJson(reader, MyJsonObject.class); 19 } 20 }; 21 MyJsonObject myjson = client.execute(httpget, rh);
1 ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy() { 2 @Override 3 public long getKeepAliveDuration(HttpResponse response, HttpContext context) { 4 long keepAlive = super.getKeepAliveDuration(response, context); 5 if (keepAlive == -1) { 6 // Keep connections alive 5 seconds if a keep-alive value 7 // has not be explicitly set by the server 8 keepAlive = 5000; 9 } 10 return keepAlive; 11 } 12 }; 13 CloseableHttpClient httpclient = HttpClients.custom().setKeepAliveStrategy(keepAliveStrat).build();
1 CloseableHttpClient httpclient = HttpClients.createDefault(); 2 try { 3 <...> 4 } finally { 5 httpclient.close(); 6 }
1 HttpContext context = <...> 2 HttpClientContext clientContext = HttpClientContext.adapt(context); 3 HttpHost target = clientContext.getTargetHost(); 4 HttpRequest request = clientContext.getRequest(); 5 HttpResponse response = clientContext.getResponse(); 6 RequestConfig config = clientContext.getRequestConfig();
1 CloseableHttpClient httpclient = HttpClients.createDefault(); 2 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000).build(); 3 HttpGet httpget1 = new HttpGet("http://localhost/1"); 4 httpget1.setConfig(requestConfig); 5 CloseableHttpResponse response1 = httpclient.execute(httpget1, context); 6 try { 7 HttpEntity entity1 = response1.getEntity(); 8 } finally { 9 response1.close(); 10 } 11 HttpGet httpget2 = new HttpGet("http://localhost/2"); 12 CloseableHttpResponse response2 = httpclient.execute(httpget2, context); 13 try { 14 HttpEntity entity2 = response2.getEntity(); 15 } finally { 16 response2.close(); 17 }
1 CloseableHttpClient httpclient = HttpClients.custom().addInterceptorLast(new HttpRequestInterceptor() { // 添加攔截器 2 public void process(final HttpRequest request, final HttpContext context) 3 throws HttpException, IOException { 4 AtomicInteger count = (AtomicInteger) context.getAttribute("count"); 5 request.addHeader("Count", Integer.toString(count.getAndIncrement())); 6 } 7 }).build(); 8 AtomicInteger count = new AtomicInteger(1); 9 HttpClientContext localContext = HttpClientContext.create(); 10 localContext.setAttribute("count", count); // 初始化數據 11 HttpGet httpget = new HttpGet("http://localhost/"); 12 for (int i = 0; i < 10; i++) { 13 CloseableHttpResponse response = httpclient.execute(httpget, localContext); 14 try { 15 HttpEntity entity = response.getEntity(); 16 } finally { 17 response.close(); 18 } 19 } 20 // 缺省了一步 localContext.getAttribute("count")
1 HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() { 2 public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { 3 if (executionCount >= 5) { 4 // Do not retry if over max retry count 5 return false; 6 } 7 if (exception instanceof InterruptedIOException) { 8 // Timeout 9 return false; 10 } 11 if (exception instanceof UnknownHostException) { 12 // Unknown host 13 return false; 14 } 15 if (exception instanceof ConnectTimeoutException) { 16 // Connection refused 17 return false; 18 } 19 if (exception instanceof SSLException) { 20 // SSL handshake exception 21 return false; 22 } 23 HttpClientContext clientContext = HttpClientContext.adapt(context); 24 HttpRequest request = clientContext.getRequest(); 25 boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); 26 if (idempotent) { 27 // Retry if the request is considered idempotent 28 return true; 29 } 30 return false; 31 } 32 }; 33 CloseableHttpClient httpclient = HttpClients.custom().setRetryHandler(myRetryHandler).build();
1 LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy(); 2 CloseableHttpClient httpclient = HttpClients.custom().setRedirectStrategy(redirectStrategy).build();
1 CloseableHttpClient httpclient = HttpClients.createDefault(); 2 HttpClientContext context = HttpClientContext.create(); 3 HttpGet httpget = new HttpGet("http://localhost:8080/"); 4 CloseableHttpResponse response = httpclient.execute(httpget, context); 5 try { 6 HttpHost target = context.getTargetHost(); 7 List<URI> redirectLocations = context.getRedirectLocations(); // 爲嘛?? 8 URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations); 9 System.out.println("Final HTTP location: " + location.toASCIIString()); 10 // Expected to be an absolute URI 11 } finally { 12 response.close(); 13 }
Plain routes are established by connecting to the target or the first and only proxy. Tunnelled routes are established by connecting to the first and tunnelling through a chain of proxies to the target. Routes without a proxy cannot be tunnelled. Layered routes are established by layering a protocol over an existing connection. Protocols can only be layered over a tunnel to the target, or over a direct connection without proxies.java