HttpClient基础学习

版权声明:本文为博主原创文章,如有转载请注明出处,谢谢。 https://blog.csdn.net/pdsu161530247/article/details/82011167

1.httpClient简介

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HttpClient 提供的主要的功能

(1)实现了所有 HTTP 的方法(GET,POST,PUT,DELETE等)

(2)支持自动转向

(3)支持 HTTPS 协议

(4)支持代理服务器等

2.httpClient使用

httpClient可以模拟用户使用浏览器

2.1导包

我这里使用的是maven,也可以直接下载httpclient的jar包

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.test</groupId>
	<artifactId>httpclient</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.5</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<!-- java编译插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

2.2模拟GET请求

也可以在url后面加上参数。

package com.test.httpclient;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class DoGET {

    public static void main(String[] args) throws Exception {
        // 1.创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 2.创建http GET请求
        HttpGet httpGet = new HttpGet("http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html");
        CloseableHttpResponse response = null;
        try {
            // 3.执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("内容长度:" + content.length());
                System.out.println(content);//响应的内容
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }
}

2.2模拟有参数GET请求

package com.httpclient.test;

import java.net.URI;

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;

public class DoGETParam {

	public static void main(String[] args) throws Exception {

		// 1.创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 2.定义请求的参数
		URI uri = new URIBuilder("http://localhost:8081/item/list").setParameter("page", "3").setParameter("rows", "10")
				.build();
		// 3.创建http GET请求
		HttpGet httpGet = new HttpGet(uri);

		CloseableHttpResponse response = null;
		try {
			//4. 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				System.out.println(content);
			}
		} finally {
			if (response != null) {
				response.close();
			}
			httpclient.close();
		}

	}

}

设置参数有两种方法

第一种addParameter,即使参数名一样也会被提交过去,可以提交表单中type="checkbox",多选按钮。

//new URIBuilder("http://localhost:8081/item/list").addParameter("a", "1").addParameter("a", "2");
//http://localhost:8081/item/list?a=1&a=2

第二种addParameter,参数名一样会被覆盖

//new URIBuilder("http://localhost:8081/item/list").setParameter("a", "1").setParameter("a", "2");
//http://localhost:8081/item/list?a=2

2.3模拟POST请求

package com.httpclient.test;

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;

public class DoPOST {

    public static void main(String[] args) throws Exception {

        // 1.创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 2.创建http POST请求
        HttpPost httpPost = new HttpPost("https://baike.baidu.com/item/%E4%BD%A0%E5%A5%BD/32416?fr=aladdin");
        // 3.设置user-agent
        //httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
        CloseableHttpResponse response = null;
        try {
            // 4.执行请求
            response = httpclient.execute(httpPost);
            System.out.println(response.getStatusLine().getStatusCode());
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }

}

2.4模拟有参数POST

package com.httpclient.test;

import java.util.ArrayList;
import java.util.List;

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;

public class DoPOSTParam {

    public static void main(String[] args) throws Exception {

        // 1.创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 2.创建http POST请求
        
        HttpPost httpPost = new HttpPost("xxxxxxxxxx");
        
        // 3.设置2个post参数,一个是scope、一个是q
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        parameters.add(new BasicNameValuePair("username", "xxxxx"));
        parameters.add(new BasicNameValuePair("password", "xxxxx"));
        // 4.构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
        // 5.将请求实体设置到httpPost对象中
        httpPost.setEntity(formEntity);
        
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
       
        CloseableHttpResponse response = null;
        try {
            // 6.执行请求
            response = httpclient.execute(httpPost);
            System.out.println(response.getStatusLine().getStatusCode());
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }

}

 

猜你喜欢

转载自blog.csdn.net/pdsu161530247/article/details/82011167