2.4 Java自动化之HttpClient发送请求

一、HttpClient 简介

      

HttpClient 是Apache Jakarta Common 下的子项目,
可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,
并且它支持 HTTP 协议最新的版本和建议
学习官网文档:http://www.httpclient.cn/cainiao.pdf

二、 如何结合httpclient发送请求

第一步: 修改Maven项目下pom.xml

<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.interfaces</groupId>
  <artifactId>InterFaceTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <!--文件拷贝时的编码-->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <!--编译时的编码-->
    <maven.compiler.encoding>UTF-8</maven.compiler.encoding>    
    
  </properties>
  <dependencies>   
	    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
		<dependency>
		    <!--httpclient理解: http://www.httpclient.cn/cainiao.pdf-->
		    <groupId>org.apache.httpcomponents</groupId>
		    <artifactId>httpclient</artifactId>
		    <version>4.5.12</version>
		</dependency>
	   
  </dependencies>
</project>

第二步:创建一个java类 

       在这里: 以get,post,patch,三种请求方式为例

请求发送,需要如下过程(对比postman发送请求理解)
* 1. new request : 创建一个请求对象
* 2. add method  : 请求方式
* 3. url填写
* 4. header 如果有参数和header就添加
* 5. 有body,则需要添加body相关信息
     - 需区分:不同请求类型,如:appication/json ,application/x-www-form-urlencoded等
* 6. send  点击发送请求
     - 发送请求,我们要承载在一个客户端上去传递,那么需要创建一个客户端
		HttpClient client = HttpClients.createDefault();
	 - 有了客户端就能发送请求了,同时获取响应
		HttpResponse res = client.execute(get);
* 7. reponse body 格式化响应体 (res 是响应对象)

     -  状态码: int status = res.getStatusLine().getStatusCode(); 
     -  响应头信息: Arrays.toString( res.getAllHeaders())
     -  响应体信息:  EntityUtils.toString(res.getEntity())

1. 发送get请求代码

package com.lujier.httpclient;

import java.io.IOException;
import java.util.Arrays;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class GetDemo {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		/* 使用httpClient发送get请求
		 * 1. new request
		 * 2. add method 
		 * 3. url填写
		 * 4. header 如果有参数和header就添加
		 * 5. send  点击发送请求
		 * 6. reponse body 格式化响应体
		 */
		String url = "http://xxxxxxxxxx";
		HttpGet get = new HttpGet(url+"/member/2077359/info");
		get.setHeader("X-Lemonban-Media-Type", "lemonban.v1");
		get.setHeader("Content-Type", "application/json");
		HttpClient client = HttpClients.createDefault();
		HttpResponse res = client.execute(get);
		Header[] header = res.getAllHeaders(); // 响应头
	    System.out.print("响应头信息:"+Arrays.toString(header) + "\n");
	    int status = res.getStatusLine().getStatusCode();
	    System.out.print("状态码::"+status+"\n");
		HttpEntity entity = res.getEntity(); // 响应体
		String body = EntityUtils.toString(entity);
	    System.out.print("响应体信息:"+body);
	
		
	}

}

2. post请求方式发送请求

package com.lujier.httpclient;

import java.io.IOException;
import java.util.Arrays;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


public class PostDemo {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		
		 // ===================   application/json ==================
		// 1. new request\2. add method\3. url填写
		String url = "http:/xxxxxxx";
		

		HttpPost post = new HttpPost(url+"/member/login");
		// 4.  body header 如果有参数和header就添加
		// 4.1 添加header
		post.setHeader("X-Lemonban-Media-Type", "lemonban.v2");
		post.setHeader("Content-Type", "application/json");
		String JsonStr = "{\"mobile_phone\":\"13221000007\",\"pwd\":\"12345678\"}";

		// 4.2 添加body
		
		// ===================   application/x-www-form-urlencoded ==================
//		String url = "http://xxxxxxxxx";
//		post.setHeader("Content-Type", "application/x-www-form-urlencoded");
//		String JsonStr = "mobilephone=13212312333&pwd=123456";
		
		post.setEntity(new StringEntity(JsonStr,"utf-8"));
		HttpClient client = HttpClients.createDefault();
		HttpResponse res = client.execute(post);
		Header[] header = res.getAllHeaders(); // 响应头
	    System.out.print("响应头信息:"+Arrays.toString(header) + "\n");
	    int status = res.getStatusLine().getStatusCode();
	    System.out.print("状态码::"+status+"\n");
		HttpEntity entity = res.getEntity(); // 响应体
		String body = EntityUtils.toString(entity);
	    System.out.print("响应体信息:"+body);
	}

}

3. Patch请求方式发送请求(类似post)

package com.lujier.httpclient;

import java.io.IOException;
import java.util.Arrays;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


public class PatchDemo {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		
		String url = "http://xxxxxxxxxxxxxxxxxx;
		HttpPatch patch = new HttpPatch(url+"/member/update");
		emonban-Media-Type", "lemonban.v1");
		patch.setHeader("Content-Type", "application/json");
		String JsonStr = "{\"member_id\":2077359,\"reg_name\":\"小史子\"}";
		patch.setEntity(new StringEntity(JsonStr,"utf-8"));
		HttpClient client = HttpClients.createDefault();
		HttpResponse res = client.execute(patch);
		Header[] header = res.getAllHeaders(); // 响应头
	    System.out.print("响应头信息:"+Arrays.toString(header) + "\n");
	    int status = res.getStatusLine().getStatusCode();
	    System.out.print("状态码::"+status+"\n");
		HttpEntity entity = res.getEntity(); // 响应体
		String body = EntityUtils.toString(entity);
	    System.out.print("响应体信息:"+body);
	}

}

通过以上3种请求,我们可以初步封装请求代码如下:

package com.lujier.utils;

import java.io.IOException;
import java.util.Arrays;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtils {
	
	public static void main(String [] args) throws Exception {
//  功能测试代码
//		String url = "http://api.xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
//		get(url);
//		String url = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
//		String JsonStr = "{\"mobile_phone\":\"13221000007\",\"pwd\":\"12345678\"}";
//        post(url,JsonStr, "json");
		String url = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
		String JsonStr = "{\"member_id\":2077359,\"reg_name\":\"小史子\"}";
        patch(url,JsonStr, "json");


	}
	
	/**
	 *  发送get请求
	 *  如果要修改请求头,需修改get源码
	 * @param url      接口的请求地址+请求参数
	 * @throws Exception
	 */
	public static void get(String url,String type) throws Exception {
		HttpGet get = new HttpGet(url);
		get = (HttpGet) header(get,type);	
		returnResponseResult(get);

	}
	
	public static void post(String url,String jsonParams,String type) throws Exception {
		HttpPost post = new HttpPost(url);
		post = (HttpPost) header(post, type);
		post.setEntity(new StringEntity(jsonParams,"utf-8"));
		returnResponseResult(post);
	}
	
	
	public static void patch(String url,String jsonParams,String type) throws Exception {
		HttpPatch patch = new HttpPatch(url);
		patch = (HttpPatch) header(patch,"json");
		patch.setEntity(new StringEntity(jsonParams,"utf-8"));
		returnResponseResult(patch);
	}
	
	
	public static HttpRequestBase header(HttpRequestBase reqObj,String type) {
		reqObj.setHeader("X-Lemonban-Media-Type", "lemonban.v1");
		if (type.trim().toLowerCase().contains("json")) {
			   reqObj.setHeader("Content-Type", "application/json");
			}
			else {
				reqObj.setHeader("Content-Type", "application/x-www-form-urlencoded");

			}
		return reqObj;
	}

	private static String returnResponseResult(HttpRequestBase reqObj) throws IOException {
       
		HttpClient client = HttpClients.createDefault();
		HttpResponse res = client.execute(reqObj);
		Header[] header = res.getAllHeaders(); // 响应头
	    System.out.print("响应头信息:"+Arrays.toString(header) + "\n");
	    int status = res.getStatusLine().getStatusCode();
	    System.out.print("状态码::"+status+"\n");
		HttpEntity entity = res.getEntity(); // 响应体
		String body = EntityUtils.toString(entity);
	    System.out.print("响应体信息:"+body);
	    return body;
	}

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值