httpClient use: ordinary GET and POST requests

1, the general request response step HttpGet

  • 1. CreateHttpClientObject, you can useHttpClients.createDefault()
  • 2, if no parameters GET request is used directly constructorHttpGet(String url)HttpGet objects can be created;
    if it is a GET request with parameters, you can first useURIBuilder(String url) Create an object, then calladdParameter(String param, String value) ,orsetParameter(String param, String value)Parameter setting request, and calls the build () method to construct a URI object. Only ConstructorHttpGet (URI uri) HttpGet to create objects.
  • 3. CreateHttpResponse ,transferHttpClient == execute (HttpUriRequest request) == transmit the requested object, the method returns aHttpResponse. transferHttpResponse的getAllHeaders()、getHeaders(String name) Or the like can be obtained in response to the first server; callHttpResponse ofgetEntity()The method can be obtained HttpEntity object content server in response to the package. Program available through the content server in response to the object. By callinggetStatusLine().getStatusCode()You can obtain the response status code;
  • 4, release the connection.

2, import dependencies

<dependency>
     <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.3.5</version>
  </dependency>
  <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.7</version>
  </dependency>
  <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.3.2</version>
  </dependency>

3, Common parameters GET request without

  • Open a url, crawling in response to the result output file html
/**
 *普通的GET请求
 */
public class DoGET {
    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet("http://www.baidu.com");
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                //请求体内容
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                //内容写入文件
                FileUtils.writeStringToFile(new File("E:\\devtest\\baidu.html"), content, "UTF-8");
                System.out.println("内容长度:"+content.length());
            }
        } finally {
            if (response != null) {
                response.close();
            }
            //相当于关闭浏览器
            httpclient.close();
        }
    }
}

4, performs a GET request with parameters

import java.io.File;
import java.net.URI;
import org.apache.commons.io.FileUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
 * 带参数的GET请求
 * 两种方式:
 *       1.直接将参数拼接到url后面 如:?wd=java
 *       2.使用URI的方法设置参数 setParameter("wd", "java")
 */
public class DoGETParam {
    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 定义请求的参数
        URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(uri);
        //response 对象
        CloseableHttpResponse response = null;
        try {
            // 执行http get请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                //内容写入文件
                FileUtils.writeStringToFile(new File("E:\\devtest\\baidu-param.html"), content, "UTF-8");
                System.out.println("内容长度:"+content.length());
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }
}

5, ordinary POST request

  • POST requests with no parameters, and set Header to disguise the browser requests
import org.apache.commons.io.FileUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;

/**
 * 常规post请求
 *    可以设置Header来伪装浏览器请求
 */
public class DoPOST {
    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建http POST请求
        HttpPost httpPost = new HttpPost("http://www.oschina.net/");
        //伪装浏览器请求
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                //内容写入文件
                FileUtils.writeStringToFile(new File("E:\\devtest\\oschina.html"), content, "UTF-8");
                System.out.println("内容长度:"+content.length());
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }
}
```java
### 6、执行带参数的POST请求

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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;

/**

  • Post request with parameters
  • Of NameValuePairs
    * /
    public class DoPOSTParam {
    public static void main (String [] args) throws Exception {
    // create objects Httpclient
    CloseableHttpClient HttpClients.createDefault HttpClient = ();
    // Create http POST request
    HttpPost httpPost = new HttpPost ( "http : / /www.oschina.net/search ");
    // set two post parameters, a scope, a is Q
    List the ArrayList new new parameters = (0);
    parameters.add (new new BasicNameValuePair (" scope "," Project ") );
    parameters.add (new new BasicNameValuePair ( "Q", "Java"));
    // configured to form a sheet-like entity
    UrlEncodedFormEntity formEntity = new new UrlEncodedFormEntity (Parameters);
    // set to the requesting entity httpPost object
    httpPost.setEntity (formEntity);
    // camouflage browser
    httpPost.setHeader ( "the User-- Agent",
    "the Mozilla / 5.0 (the Windows NT 6.1; Win64; x64-) AppleWebKit / 537.36 (KHTML, like the Gecko) the Chrome / 56.0.2924.87 Safari / 537.36");
    CloseableHttpResponse Response = null;
    the try {
    // execution request
    Response = httpclient.execute (HttpPost);
    // determines whether the state is returned 200 is
    iF {(response.getStatusLine () getStatusCode () == 200 is.)
    String Content = EntityUtils.toString (response.getEntity (), "UTF-8");
    // write the file contents
    FileUtils.writeStringToFile (new new file ( "E: \ DevTest \ oschina-param.html"), content, "UTF-8");
    System.out.println ( " content-length: "+ content.length ());
    }
    } the finally {
    ! IF (Response = null) {
    response.close ();
    }
    httpclient.close ();
    }
    }
    }

Published 134 original articles · won praise 91 · views 160 000 +

Guess you like

Origin blog.csdn.net/weixin_44588495/article/details/102930161