HTTP request (is closeablehttpclient an implementation of HTTP protocol rules?) )

Source: Internet
Author: User
Tags http post

Initiate an interactive request for the HTTP protocol:
Want to initiate can be initiated (in line with the World Wide Web System developed HTTP protocol can be specified in the format of the request header, request body, etc.), but can not return and return what is determined by the target interface. If a problem is returned, is the generated status code detected and returned by the World Wide Web system? Why can background developers also set status codes?

Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.ClientProtocolException;
Import Org.apache.http.client.ResponseHandler;
Import Org.apache.http.client.config.RequestConfig;
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.TrustStrategy;
Import org.apache.http.entity.ByteArrayEntity;
Import org.apache.http.impl.client.CloseableHttpClient;
Import org.apache.http.impl.client.HttpClients;
Import Org.apache.http.ssl.SSLContextBuilder;
Import Org.apache.http.util.EntityUtils;

Import Javax.net.ssl.HostnameVerifier;
Import Javax.net.ssl.SSLContext;
Import javax.net.ssl.SSLSession;
Import java.io.IOException;
Import java.security.KeyManagementException;
Import java.security.KeyStoreException;
Import java.security.NoSuchAlgorithmException;
Import java.security.cert.CertificateException;
Import Java.security.cert.X509Certificate;

public class Httpclientutil {

/**
* Send HTTP GET request
* @param URL URL
* @return Response Body String
* @throws IOException IOException
*/
public static string HttpGet (string url) throws IOException {

String Responsestr;

Closeablehttpclient httpClient = Createsslclientdefault ();

HttpGet httpget = new HttpGet (URL);
Requestconfig requestconfig = Requestconfig.custom (). Setconnecttimeout (45000). build ();
Httpget.setconfig (Requestconfig);

responsehandler<string> ResponseHandler = new Responsehandler<string> () {

@Override
Public String handleresponse (final HttpResponse response) throws IOException {
int status = Response.getstatusline (). Getstatuscode ();
if (Status >= && status < 300) {
httpentity entity = response.getentity ();
return entity! = null? Entityutils.tostring (entity): null;
} else {
throw new Clientprotocolexception ("Unexpected message Status:" + status);
}
}

};

Responsestr = Httpclient.execute (HttpGet, ResponseHandler);

return responsestr;
}

/**
* Send an HTTP POST request
* @param URL URL
* @return Response Body String
* @throws IOException IOException
*/
public static string HttpPost (string URL, String body) throws IOException {

String Responsestr;

Closeablehttpclient httpClient = Createsslclientdefault ();

HttpPost HttpPost = new HttpPost (URL);
Httppost.setheader ("Content-type", "Application/json");

Requestconfig requestconfig = Requestconfig.custom (). Setconnecttimeout (45000). build ();
Httppost.setconfig (Requestconfig);

httpentity entity = new Bytearrayentity (body.getbytes ("Utf-8"));
Httppost.setentity (entity);

responsehandler<string> ResponseHandler = new Responsehandler<string> () {

@Override
Public String handleresponse (final HttpResponse response) throws IOException {
int status = Response.getstatusline (). Getstatuscode ();
if (Status >= && status < 300) {
httpentity entity = response.getentity ();
return entity! = null? Entityutils.tostring (entity): null;
} else {
throw new Clientprotocolexception ("Unexpected message Status:" + status);
}
}

};

Responsestr = Httpclient.execute (HttpPost, ResponseHandler);

return responsestr;
}

/**
* Create a httpclient that can send HTTPS requests
* @return Closeablehttpclient
*/
private static Closeablehttpclient Createsslclientdefault () {
try {
Sslcontext sslcontext = new Sslcontextbuilder (). loadtrustmaterial (NULL, new Truststrategy () {
Trust all
public boolean istrusted (x509certificate[] chain, String authtype) throws Certificateexception {
return true;
}
}). build ();
Sslconnectionsocketfactory SSLSF = new Sslconnectionsocketfactory (Sslcontext, New Myhostnameverifier ());
Return Httpclients.custom (). Setsslsocketfactory (SSLSF). build ();
} catch (Keymanagementexception | nosuchalgorithmexception | Keystoreexception e) {
E.printstacktrace ();
}
return Httpclients.createdefault ();
}

Sslpeerunverifiedexception:host Name Err
private static class Myhostnameverifier implements Hostnameverifier {
@Override
public boolean verify (String arg0, sslsession arg1) {
return true;
}

}

}


HTTP request (is closeablehttpclient an implementation of HTTP protocol rules?) )

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.