Java http request methods: HttpURLConnection and HttpClient,

Source: Internet
Author: User
Tags response code

Java http request methods: HttpURLConnection and HttpClient,

1. You need to understand some conceptual things, such as the Http protocol and some top-level topics.

2. General steps of HttpURLConnection: create URL object = get HttpURLConnection object instance of URL = set HTTP Request Method = set timeout and message header = determine server response code = get the input stream returned by the server = turn off the HTTP Connection

2.1 GET request example

// Create a URL object. xxx is the server's APIURL url = new URL ("xxx"); // call the openConnection () of the URL object to obtain the HttpURLConnection object instance HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // The Request Method is GETconn. setRequestMethod ("GET"); // sets the connection timeout to 5 seconds conn. setConnectTimeout (5000); // The server returns something. First, judge if (conn. getResponseCode () = 200) {// use the getInputStream () method to obtain the InputStream in = conn. getInputStream (); byte [] data = read (in); // convert the stream to a binary array. read () writes the conversion method String html = new String (data, "UTF-8"); System. out. println (html); in. close ();}

Ps: the above steps are based on the premise that the server interface is normal, of course, the exception must be handled in addition, the request header is set as needed, and the input stream returned by the server is converted as needed, in addition, sometimes a thread needs to be opened for network requests.

2.2 POST requests: The POST requests are basically the same as GET requests. When setting relevant parameters, you must set allow input and output, and the POST method cannot be cached. You must manually set it to false.

// Create a URL object. xxx is the server's APIURL url = new URL ("xxx"); // call the openConnection () of the URL object to obtain the HttpURLConnection object instance HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // The Request Method is GETconn. setRequestMethod ("POST"); // sets the connection timeout to 5 seconds conn. setConnectTimeout (5000); // allow Input and Output conn. setDoInput (true); conn. setDoOutput (true); // the conn cannot be cached. setUseCaches (false); // at least two request headers to be set conn. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); // The output stream contains the data to be sent, note that the data format encoding OutputStream op = conn. getOutputStream (); op. write (new String ("name = zhylioooo "). getBytes (); // if (conn. getResponseCode () = 200) {// use the getInputStream () method to obtain the InputStream in = conn. getInputStream (); byte [] data = read (in); // convert stream to binary array, read () is the conversion method String html = new String (data, "UTF-8 "); system. out. println (html); in. close ();}

3. HttpClient usage steps: Create HttpClient object = and create an Http request object (different GET and POST objects) = "Set Request Parameters =" execution request = "get response object =" Process Response object = "close corresponding object =" close HttpClient

3.1. GET

// Create the httpclient object CloseableHttpClient httpclient = HttpClients. createDefault (); // create the GET object HttpGet httpget = new HttpGet ("xxx"); // xxx is the Server API // execute the request CloseableHttpResponse response = httpclient.exe cute (httpget ); if (response. getStatusLine (). getStatusCode () = 200) {HttpEntity entity = response. getEntity (); // the required content is in entity. You can operate String detail = EntityUtils on the data here. toString (entity, "UTF-8"); System. out. println (detail);} response. close (); httpclient. close ();

You can useURIBuilderTool class to simplify

URI uri = new URIBuilder()        .setScheme("https")        .setHost("xxx")        .setPath("/xxx")        .setParameter("key1", "value1")        .setParameter("key2", "value2")        .build();HttpGet httpget = new HttpGet(uri);

3.2. POST: POST is generally used to submit some special things with a variety of content. HttpClient provides different data containers for different content, such as the most common string (StringEntity ), byteArrayEntity, InputStreamEntity, and FileEntity.InputStreamEntityIt cannot be repeated because it can only be read once from the underlying data stream. It is generally recommended to implement a customHttpEntityInstead of using genericInputStreamEntity.FileEntityIt can be a good starting point:

File file = new File("xxx.txt");FileEntity entity = new FileEntity(file,     ContentType.create("text/plain", "UTF-8"));        HttpPost httppost = new HttpPost("xxx");httppost.setEntity(entity);

The most common form data of POST: After an HttpPost object is created, parameters waiting for submission are stored in the NameValuePair set, passed to UrlEncodedFormEntity, and setEntity (entity) is called, httpClient.exe cute (HttpPost:

List<NameValuePair> formparams = new ArrayList<NameValuePair>();formparams.add(new BasicNameValuePair("name", "zhylioooo"));formparams.add(new BasicNameValuePair("pswd", "123456"));UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);HttpPost httppost = new HttpPost("xxx");httppost.setEntity(entity);

4. HttpURLConnection and HttpClient are rarely written in actual development. They are all third-party network request frameworks encapsulated by others, such as Volley, android-async-http, and loopj, because network operations involve Asynchronization and multithreading, It is very troublesome to write it by yourself, so the actual development still uses a third party directly.

5. HttpClient jar package: https://pan.baidu.com/s/1gfjHi2B

Related Article

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.