In web development, we often need to simulate post and GET requests. Currently, httpclient3.x is widely used on the Internet. However, httpclient4.x has been released for several years, and 4. changed to httpcomponents after X, which is obviously a trend in the future.
Httpclient in Apache httpcomponents4.x is a good tool that complies with the http1.1 specification and is implemented based on the httpcore class package. However, httpcomponents4.x has changed significantly compared with httpclient3.x APIs. It has been divided into httpclient, httpcore, httpasyncclient, and other components. The encoding during post and GET request simulation has also changed significantly.
The following is a routine for httpclient4.3.4 to simulate a GET request.
Public void requestget (string urlwithparams) throws exception {closeablehttpclient httpclient = httpclientbuilder. create (). build (); // httpget = new httpget ("http://www.baidu.com/"); httpget = new httpget (urlwithparams); // configure the request timeout setting requestconfig = requestconfig. custom (). setconnectionrequesttimeout (50 ). setconnecttimeout (50 ). setsockettimeout (50 ). build (); httpget. setconfig (requestconfig); closeablehttpresponse response = httpclient.exe cute (httpget); system. out. println ("statuscode->" + response. getstatusline (). getstatuscode (); httpentity entity = response. getentity (); string jsonstr = entityutils. tostring (entity); //, "UTF-8"); system. out. println (jsonstr); httpget. releaseconnection ();}
Httpclient4.3.4 routines used to simulate POST requests
public void requestPost(String url,List<NameValuePair> params) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse response = httpclient.execute(httppost); System.out.println(response.toString()); HttpEntity entity = response.getEntity(); String jsonStr = EntityUtils.toString(entity, "utf-8"); System.out.println(jsonStr); httppost.releaseConnection();}
When running the POST method, you can
public static void main(String[] args){ try { String loginUrl = "http://localhost:8080/yours"; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", "zhang")); params.add(new BasicNameValuePair("passwd", "123")); requestPost(loginUrl,params); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}
Finally, the routine of the httpcomponents official website is provided.
Http://hc.apache.org/httpcomponents-core-4.3.x/examples.html