Httpclient sends a request, httpclient sends
HTTP client version 4.1Send a post request
public static JSONObject post(String url,JSONObject json){ HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); JSONObject response = null; try { StringEntity s = new StringEntity(json.toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/json"); post.setEntity(s); HttpResponse res = client.execute(post); if(res.getStatusLine().getStatusCode() == HttpStatus.OK.value()){ HttpEntity entity = res.getEntity(); String charset = EntityUtils.getContentCharSet(entity); response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset))); } } catch (Exception e) { throw new RuntimeException(e); } return response; }
Simulate form submission:
private static HttpPost postForm(String url, Map<String, String> params){ HttpPost httpost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList <NameValuePair>(); Set<String> keySet = params.keySet(); for(String key : keySet) { nvps.add(new BasicNameValuePair(key, params.get(key))); } try { log.info("set utf-8 form entity to httppost"); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return httpost; }
Get request
public static String get(String url) { DefaultHttpClient httpclient = new DefaultHttpClient(); String body = null; log.info("create httppost:" + url); HttpGet get = new HttpGet(url); body = invoke(httpclient, get); httpclient.getConnectionManager().shutdown(); return body; }
Initiate a post request and set timeout:
Note that different versions of Apis set timeout are different.
Note that the timeout period in 3 is as follows:
1. Connection Timeout: connectionTimeout refers to the connection wait time of a url.
2. Data Reading Time-out: soTimeout refers to the connection to the previous url and gets the response wait time.
3. SocketTimeout: defines the timeout time for the Socket to read data, that is, the time needed to wait for the response data to be obtained from the server.
Public static String sendPostRequest (String url, String str, String contentType, String charset) {// HttpParams httpParams = new BasicHttpParams (); // version 4.1 // HttpConnectionParams. setConnectionTimeout (httpParams, 5000); // establishes the connection timeout time to prevent the call url from being a dead link and consuming server io // HttpConnectionParams. setSoTimeout (httpParams, 3000); // response timeout // CloseableHttpClient httpClient = new DefaultHttpClient (); RequestConfig. builder requestBuil Der = RequestConfig. custom (); // version 4.3.5 requestBuilder = requestBuilder. setConnectTimeout (5000); // requestBuilder = requestBuilder. setConnectionRequestTimeout (100); HttpClientBuilder = HttpClientBuilder. create (); builder. setDefaultRequestConfig (requestBuilder. build (); CloseableHttpClient httpClient = builder. build (); HttpPost post = new HttpPost (url); // RequestConfig requestConfig = Reques TConfig. custom (). setSocketTimeout (2000 ). setConnectTimeout (2000 ). build (); // post. setConfig (requestConfig); post. setHeader ("Content-Type", contentType); ResponseHandler <String> responseHandler = new BasicResponseHandler (); String response = null; try {post. setEntity (new StringEntity (str, charset); long start = System. currentTimeMillis (); try {response = httpClient.exe cute (post, responseHandler );} Catch (Exception ConnectionTimeoutException) {// connection establishment timeout Exception long p = System. currentTimeMillis ()-start; log. error ("sendPostRequest has a ConnectionTimeoutException timeout =>" + p + "" + url);} finally {// httpClient. getConnectionManager (). shutdown (); post. releaseConnection () ;}} catch (Exception e) {log. error ("executing HTTP Post request" + url + ", an exception occurred! ", E);} return response ;}
What should I do if HttpClient sends an xml string? For more information, see the following question.
If it is the Servlet HttpClientTest above, you only need to configure this servlet in web. xml. During the request, you can request the servlet address. If you want to write a jsp by yourself, the first part of your jsp should be the content in the doPost method in the HttpClientTest class (but the xml output returned in the end is not the same ), jsp does not need to configure interceptor, filter, and so on. It can be accessed directly by address. Therefore, whether it is servlet or jsp. Make sure that the data you return is an xml content. I suggest you use servlet for writing, which is simpler and more convenient.
Let's take a look at the situation. When httpclient is used to send http, the connection times out frequently.
If it is a public network, the timeout is normal. Just handle it.