A simple example of the process by which java sends an HttpClient request and receives the result of a request
- 2020-05-16 06:56:39
- OfStack
1.
1. Write an HttpRequestUtils utility class, including post requests and get requests
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);
// logging /** * httpPost * @param url The 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 parameter * @param noNeedResponse There is no need to return the result * @return */
public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
//post Request return result
DefaultHttpClient httpClient = new DefaultHttpClient();
JSONObject jsonResult = null;
HttpPost method = new HttpPost(url);
try {
if (null != jsonParam) {
// Solve the problem of Chinese garbled code
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 from the server json String data **/
str = EntityUtils.toString(result.getEntity());
if (noNeedResponse) {
return null;
}
/** the json String conversion 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 The path * @return */
public static JSONObject httpGet(String url){
//get Request return 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 from the server json String data **/
String strResult = EntityUtils.toString(response.getEntity());
/** the json String conversion 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 and send Http request
3. MVC configuration file set Controller scan directory
<!-- Automatic and scan only @Controller -->
<context:component-scan base-package="com.wiselong.multichannel" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
4. Receive the Http request
Receive the post request
@Controller
@RequestMapping(value = "/api/platform/exceptioncenter/exceptioninfo")
public class ExceptionInfoController {
// injection
@Autowired
private ExceptionInfoBiz exceptionInfoBiz;
/**
* Create an exception information request
* @param requestBody Request message content
* @param request Request header
* @return jsonObject
*/
@RequestMapping(
value="/create",
method = RequestMethod.POST
)
public ModelAndView createExceptionInfo(@RequestBody String requestBody, HttpServletRequest request) {
JSONObject jsonObject = JSONObject.fromObject(requestBody);
ComExceptionInfo comExceptionInfo = new ComExceptionInfo();
comExceptionInfo.setProjectName(jsonObject.getString("projectName"));
comExceptionInfo.setTagName(jsonObject.getString("tagName"));
exceptionInfoBiz.insert(comExceptionInfo);
// Return request result
JSONObject result= new JSONObject();
result.put("success", "true");
return new ModelAndView("", ResponseUtilsHelper.jsonSuccess(result.toString()));
}
}
Receive the get request
@Controller
@RequestMapping(value="/api/platform/messagecenter/messages/sms")
public class SmsController {
@Autowired
SmsSendBiz smsSendBiz;
/**
* Receive cell phone number and content to SMS send table insert 1 records
* @param requestbody Request message content
* @param request Request header
* @return jsonObject
*/
@RequestMapping(
value="/send",
method= RequestMethod.GET
)
public ModelAndView sendSms(@RequestBody String requestbody, HttpServletRequest request) {
// Get request URL and url Parameters to be transmitted later
String url = request.getRequestURL() + "?" + request.getQueryString();
url = BuildRequestUrl.decodeUrl(url);
String telePhone = RequestUtils.getStringValue(request, "telePhone");
String content = RequestUtils.getStringValue(request, "content");
smsSendBiz.insertTtMsQuequ(telePhone,content);
return new ModelAndView("", ResponseUtilsHelper.jsonResult("", true));
}
}
2.
get
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
public class H_client_get {
public static void main(String[] args) throws IOException {
// new Class object
HttpClient client = new HttpClient();
// use GET methods with URL The server interacts
// HttpMethod method = new GetMethod("http://192.168.111.128/bak/regist.php?email=admin@admin.com&password=1234567&re_password=1234567&username=admin&nickname= The administrator ");
HttpMethod method = new GetMethod("http://192.168.111.128/bak/login.php?username=");
// use GET methods , the implementation and url Server connection
client.executeMethod(method);
// Data stream output
// method.getResponseBodyAsStream Create the byte stream object as inputStream
InputStream inputStream = method.getResponseBodyAsStream();
// InputStreamReader(inputStream) Byte stream to character stream BufferedReader Encapsulated as a buffered character stream object
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
// StringBuffer Is a string variable whose object can be expanded and modified create 1 empty StringBuffer The object of the class
StringBuffer stringBuffer = new StringBuffer();
// Define string constants
String str= "";
// br Character stream assignment to str String constant str Is not equal to empty According to the line of the output
while((str = br.readLine()) != null){
// StringBuffer Is a string variable whose object can be expanded and modified will str Data given stringBuffer
stringBuffer .append(str );
}
// Loop the output as a string stringBuffer
System.out.println(stringBuffer.toString());
// Shut down method the httpclient The connection
method.releaseConnection();
}
}
post
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.*;
public class H_client_post {
public static void main(String[] args) throws IOException {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("http://192.168.111.128/bak/login_post.php");
// The value of the form field , both post The incoming key=value
NameValuePair[] date = { new NameValuePair("username","admin"),new NameValuePair("password","123457")};
//method Use form thresholds
method.setRequestBody(date);
// Submit the form
client.executeMethod(method);
// Character stream byte stream Loop output, same get explain
InputStream inputStream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
StringBuffer stringBuffer = new StringBuffer();
String str= "";
while((str = br.readLine()) != null){
stringBuffer .append(str );
}
System.out.println(stringBuffer.toString());
method.releaseConnection();
}
}
3.
Http agreement believe I don't need to say more, the importance of HttpClient compared with the traditional JDK bring URLConnection, increases the ease of use and flexibility (specific distinction, we discuss it later) in the future, it is not only the client sends Http request easier, but also convenient for developer testing interface (based on Http protocol), which improves the development efficiency, is convenient to improve the robustness of the code. Therefore, it is very important to master HttpClient. After mastering HttpClient, I believe I will have a deeper understanding of the Http protocol.
1. Introduction
HttpClient is a subproject under Apache Jakarta Common to provide an efficient, up-to-date, and features-rich client programming toolkit that supports the HTTP protocol, and it supports the latest versions and recommendations of the HTTP protocol. HttpClient has been used in many projects, such as Cactus and HTMLUnit, two other well-known open source projects on Apache Jakarta.
2. The characteristics of
1. Standard based, pure java language. Http1.0 and Http1.1 are realized
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 transparent connections through the Http agent.
5. The https connection of the tunnel is established through the Http agent using the CONNECT method.
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos certification schemes
7. Plug-in - style custom authentication scheme.
8. The portable and reliable socket factory makes it easier to use the third party solution.
9. The connection manager supports multi-threaded applications. Support for setting the maximum number of connections, as well as setting the maximum number of connections per host to find and close out-of-date connections.
10. Automatic processing of Cookie in Set-Cookie.
11. Plug-in style custom Cookie policy.
12. The output stream of Request prevents 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. KeepAlive is used in http1.0 and http1.1 to maintain persistent connections.
15. Get response code and headers sent by the server directly.
16. Ability to set connection timeout.
17. Experimental support http1.1 response caching
18. Source code based on Apache License is freely available.
3. Method of use
Using HttpClient to send a request and receive a response is simple, as shown in the following steps.
1. Create the HttpClient object.
2. Create an instance of the request method and specify request URL. If you need to send an GET request, create an HttpGet object; If you need to send an 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 request parameters; For the HttpPost object, you can also call the setEntity(HttpEntity entity) method to set the request parameters.
4. Call execute(HttpUriRequest request) of HttpClient object to send the request, and this method returns one HttpResponse.
5. The response header of the server can be obtained by calling getAllHeaders(), getHeaders(String name) and other methods of HttpResponse; The getEntity() method of HttpResponse is called to obtain the HttpEntity object, which wraps the response content of the server. The program can use this object to get the server's response content.
Release the connection. Regardless of whether the execution method is successful, the connection must be released
Example 4.
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class HttpClientTest {
@Test
public void jUnitTest() {
get();
}
/**
* HttpClient The 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.
// loading keyStore d:\\tomcat.keystore
trustStore.load(instream, "123456".toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (Exception ignore) {
}
}
// Believe in oneself CA And all self-signed certificates
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
// Only allowed TLSv1 agreement
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
// create http request (get way )
HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.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();
}
}
}
}
/**
* post Way to submit the form (simulate user login request)
*/
public void postForm() {
// Create the default httpClient The instance .
CloseableHttpClient httpclient = HttpClients.createDefault();
// create httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// Create a parameter queue
List<namevaluepair> formparams = 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 , Release resources
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* send post The request accesses the local application and returns different results depending on the parameters passed
*/
public void post() {
// Create the default httpClient The instance .
CloseableHttpClient httpclient = HttpClients.createDefault();
// create httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// Create a parameter queue
List<namevaluepair> formparams = new ArrayList<namevaluepair>();
formparams.add(new BasicNameValuePair("type", "house"));
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 , Release resources
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* send 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());
// perform get request .
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// Get the response entity
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// Print response state
System.out.println(response.getStatusLine());
if (entity != null) {
// Print the 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("------------------------------------");
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// Close the connection , Release resources
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Upload a 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></namevaluepair>