one.
1. Write a HttpRequestUtils tool class, including post request and get request
package com.brainlong.framework.util.httpclient; import net.sf.json.JSONObject;import org.apache.commons.httpclient.HttpStatus;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory; import java.io.IOException;import java.net.URLDecoder; public class HttpRequestUtils { private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class); //Log/** * httpPost * @param url path * @param jsonParam parameter * @return */ public static JSONObject httpPost(String url,JSONObject jsonParam){ return httpPost(url, jsonParam, false); } /** * post request* @param url url address* @param jsonParam Parameters* @param noNeedResponse No need to return result* @return */ public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){ //post request returns resultDefaultHttpClient httpClient = new DefaultHttpClient(); JSONObject jsonResult = null; HttpPost method = new HttpPost(url); try { if (null != jsonParam) { //Solve the Chinese garbled problem StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); method.setEntity(entity); } HttpResponse result = httpClient.execute(method); url = URLDecoder.decode(url, "UTF-8"); /**The request was sent successfully and received a response**/ if (result.getStatusLine().getStatusCode() == 200) { String str = ""; try { /**Read the json string data returned by the server**/ str = EntityUtils.toString(result.getEntity()); if (noNeedResponse) { return null; } /**Convert json string to json object**/ jsonResult = JSONObject.fromObject(str); } catch (Exception e) { logger.error("post request submission failed:" + url, e); } } } catch (IOException e) { logger.error("post request submission failed:" + url, e); } return jsonResult; } /** * Send get request* @param url path* @return */ public static JSONObject httpGet(String url){ //get request returns result JSONObject jsonResult = null; try { DefaultHttpClient client = new DefaultHttpClient(); //Send get request HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); /**The request was sent successfully and received a response**/ if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { /**Read the json string data returned by the server**/ String strResult = EntityUtils.toString(response.getEntity()); /**Convert json string to json object**/ jsonResult = JSONObject.fromObject(strResult); url = URLDecoder.decode(url, "UTF-8"); } else { logger.error("get request submission failed:" + url); } } catch (IOException e) { logger.error("get request submission failed:" + url, e); } return jsonResult; }}2. Write business code to send Http request
3. MVC configuration file settings Controller scanning directory
<!-- Automatic scan and only scan @Controller --><context:component-scan base-package="com.wiselong.multichannel" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.steretype.Controller" /></context:component-scan>
4. Receive Http request
Receive post request
@Controller@RequestMapping(value="/api/platform/exceptioncenter/exceptioninfo")publicclassExceptionInfoController{//Inject @AutowiredprivateExceptionInfoBizexceptionInfoBiz;/***Create exception information request*@paramrequestBody request message content*@p aramrequest request message header*@returnjsonObject*/@RequestMapping(value="/create",method=RequestMethod.POST)publicModelAndViewcreateExceptionInfo(@RequestBodyStringrequestBody,HttpServletRequestrequest){JSONObjectjsonObject ct=JSONObject.fromObject(requestBody);ComExceptionInfocomExceptionInfo=newComExceptionInfo();comExceptionInfo.setProjectName(jsonObject.getString("projectName"));comExceptionInfo.setTagName(jsonObject.getString("projectName"));comExceptionInfo.setTagName(jsonObject.getStr ing("tagName"));exceptionInfoBiz.insert(comExceptionInfo);//Return the request result JSONObjectresult=newJSONObject();result.put("success","true");returnnewModelAndView("",ResponseUtilsHelper.jsonSuccess(result.toString()));}}Receive get request
@Controller@RequestMapping(value="/api/platform/messagecenter/messages/sms")publicclassSmsController{@AutowiredSmsSendBizsmsSendBiz;/***Receive mobile phone number and content and insert a record into the SMS send table*@paramrequestbody request message Content *@paramrequest request message header*@returnjsonObject*/@RequestMapping(value="/send",method=RequestMethod.GET)publicModelAndViewsendSms(@RequestBodyStringrequestbody,HttpServletRequestrequest){ //Get the parameters transmitted after the request URL and url Stringurl=request.getRequestURL()+"?"+request.getQueryString();url=BuildRequestUrl.decodeUrl(url);StringtelePhone=RequestUtils.getStringValue(request,"telePhon e");Stringcontent=RequestUtils.getStringValue(request,"content");smsSendBiz.insertTtMsQuqu(telePhone,content);returnnewModelAndView("",ResponseUtilsHelper.jsonResult("",true));}}two.
get
importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importorg.apache.commons.httpclient.HttpClient;importorg.apache.commons.httpclient.HttpMethod;importorg.apache.commons.httpclient.methods.GetMethod;publicclassH_client_get{publicstaticvoidmain(String[]args)throwsIOExcep tion{//new class object HttpClientclient=newHttpClient();//Use the GET method to interact with the URL server//HttpMethodmethod=newGetMethod("http://192.168.111.128/bak/[email protected]&passwor d=1234567&re_password=1234567&username=admin&nickname=admin");HttpMethodmethod=newGetMethod("http://192.168.111.128/bak/login.php?username=");//Use the GET method to implement the client connection to the url server .executeMethod(method);//Data stream output//method.getResponseBodyAsStream Create a byte stream object as inputStreamInputStreaminputStream=method.getResponseBodyAsStream();//InputStreamReader(inputStream am) The byte stream is converted into a character stream BufferedReader is encapsulated into a character stream object with buffered. BufferedReaderbr=newBufferedReader(newInputStreamReader(inputStream,"UTF-8")); //StringBuffer is a string variable, and its object can be expanded and modified to create an empty StringBuf fer class object StringBufferstringBuffer=newStringBuffer();//Define string constant Stringstr="";//Assigning a string stream to str string constant str does not equal empty output while ((str=br.readLine()))!=null){//StringBuffer is a string variable, and its object can be augmented and modified to assign str data to stringBufferstringBuffer.append(str);}//Output stringBufferSystem.out.println(stringBuffer.toString());//Close the method httpclient connection method.releaseConnection();}}post
importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importorg.apache.commons.httpclient.methods.PostMethod;importorg.apache.commons.httpclient.*;publicclassH_client_post{pu blicstaticvoidmain(String[]args)throwsIOException{HttpClientclient=newHttpClient();PostMethodmethod=newPostMethod("http://192.168.111.128/bak/login_post.php");//The value of the form field, both the key=valueNameValuePair[]date={newNameValuePair("username", "admin"),newNameValuePair("password","123457")};//method uses the form threshold method.setRequestBody(date);//Submit form client.executeMethod(method);// Character streaming byte streaming loop output, same as get explanation InputStreaminputStream=method.getResponseBodyAsStream();BufferedReaderbr=newBufferedRead er(newInputStreamReader(inputStream,"UTF-8"));StringBufferstringBuffer=newStringBuffer();Stringstr="";while((str=br.readLine())!=null){stringBuffer.append(str);}System.out.println(stringBuffer.toString()); method.releaseConnection();}}three.
I don't need to say more about the importance of the Http protocol. Compared with the URLConnection that comes with traditional JDK, HttpClient increases ease of use and flexibility (the specific difference will be discussed later). It not only makes it easier for the client to send Http requests, but also facilitates the developer's test interface (based on the Http protocol), which improves the development efficiency and also facilitates the code robustness. Therefore, it is very important and compulsory to master HttpClient. After mastering HttpClient, I believe that my understanding of the Http protocol will be more in-depth.
1. Introduction
HttpClient is a sub-project under Apache Jakarta Common to provide efficient, latest, feature-rich client programming toolkits that support HTTP protocol, and it supports the latest versions and suggestions of the HTTP protocol. HttpClient has been used in many projects, such as two other well-known open source projects on Apache Jakarta, Cactus and HTMLUnit, both use HttpClient.
2. Characteristics
1. Standard-based, pure Java language. Implemented Http1.0 and Http1.1
2. All Http methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) are implemented in an extensible object-oriented structure.
3. Support HTTPS protocol.
4. Establish a transparent connection through the Http proxy.
5. Use the CONNECT method to establish a https connection to the tunnel through the Http proxy.
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos certification scheme.
7. Plug-in custom authentication solution.
8. Portable and reliable socket factory makes it easier to use third-party solutions.
9. Connection Manager supports multi-threaded applications. It supports setting the maximum number of connections, and also supports setting the maximum number of connections per host, discovering and closing expired connections.
10. Automatically handle cookies in Set-Cookies.
11. Plugin custom cookie policy.
12. The output stream of the Request can prevent the contents of the stream from being buffered directly to the socket server.
13. The input stream of Response can effectively read the corresponding content directly from the socket server.
14. Keep persistent connections with KeepAlive in http1.0 and http1.1.
15. Directly obtain the response code and headers sent by the server.
16. Set the ability to time out the connection.
17. Experimental support for http1.1 response caching.
18. The source code is available for free based on Apache License.
3. How to use
It is very simple to use HttpClient to send requests and receive responses, and generally requires the following steps.
1. Create an HttpClient object.
2. Create an instance of the request method and specify the request URL. If you need to send a GET request, create an HttpGet object; if you need to send a POST request, create an HttpPost object.
3. If you need to send request parameters, you can call the setParams (HetpParams params) method common to HttpGet and HttpPost to add the request parameters; for HttpPost objects, you can also call the setEntity (HttpEntity entity) method to set the request parameters.
4. Call the execution(HttpUriRequest request) of the HttpClient object to send a request, and this method returns an HttpResponse.
5. Calling HttpResponse's getAllHeaders(), getHeaders(String name) and other methods can get the server's response header; calling HttpResponse's getEntity() method can get the HttpEntity object, which wraps the server's response content. The program can obtain the server's response content through this object.
6. Release the connection. The connection must be released regardless of whether the execution method is successful or not.
IV. Examples
package com.test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import javax.net.ssl.SSLContext; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.junit.Test; public class HttpClientTest { @Test public void jUnitTest() { get(); } /** * HttpClient connection SSL */ public void ssl() { CloseableHttpClient httpclient = null; try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream Instream = new FileInputStream(new File("d://tomcat.keystore")); try { 54. // Load keyStore d://tomcat.keystore trustStore.load(instream, "123456".toCharArray()); } catch (CertificateException e) { e.printStackTrace(); } finally { try { enterstream.close(); } catch (Exception ignore) { } } // Trust your own CA and all self-signed certificates SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); // Only use of the TLSv1 protocol SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); // Create http request (get method) HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action"); System.out.println("executing request" + httpget.getRequestLine()); CloseableHttpResponse response = httppclient.execute(httpget); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); System.out.println(EntityUtils.toString(entity)); EntityUtils.consume(entity); } } finally { response.close(); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } finally { if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } } } /** * Submit the form in post (simulate user login request) */ public void postForm() { // Create the default httpClient instance. CloseableHttpClient httpclient = HttpClients.createDefault(); // Create httppost HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action"); // Create parameter queue List<namevaluepair> forparams = new ArrayList<namevaluepair>(); formparams.add(new BasicNameValuePair("username", "admin")); formparams.add(new BasicNameValuePair("password", "123456")); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("--------------------------------------"); System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); System.out.println("--------------------------------------"); } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // Close the connection and release the resource try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Send a post request to access the local application and return different results according to the passed parameters*/ public void post() { // Create the default httpClient instance. CloseableHttpClient httppclient = HttpClients.createDefault(); // Create httppost HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action"); // Create parameter queue List<namevaluepair> forparams = new ArrayList<namevaluepair>(); forparams.add(new BasicNameValuePair("type", "house")); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(forparams, "UTF-8"); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("--------------------------------------"); System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); System.out.println("--------------------------------------"); } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // Close the connection and release the resource try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Send a get request*/ public void get() { CloseableHttpClient httpclient = HttpClients.createDefault(); try { // Create httpget. HttpGet httpget = new HttpGet("http://www.baidu.com/"); System.out.println("executing request " + httpget.getURI()); // Execute the get request. CloseableHttpResponse response = httpclient.execute(httpget); try { // Get the response entity HttpEntity entity = response.getEntity(); System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Print response content length System.out.println("Response content length: " + entity.getContentLength()); // Print response content System.out.println("Response content: " + EntityUtils.toString(entity)); } System.out.println("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- } catch (IOException e) { e.printStackTrace(); } finally { // Close the connection and release the resource try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Upload the file*/ public void upload() { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action"); FileBody bin = new FileBody(new File("F://image//sendpix0.jpg")); StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }</namevaluepair></namevaluepair></namevaluepair>The above simple example of the process of sending HttpClient requests and receiving request results in Java is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.