httpcomponents.httpclient 使用

Posted dream_heheda

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了httpcomponents.httpclient 使用相关的知识,希望对你有一定的参考价值。

1.使用场景

两个Spring Boot 项目DemoA 和 DemoB。DemoA 需要调用DemoB提供的接口,并且传递数据,接收dmeoB的返回数据。

2. Demo B 

1.添加依赖

<properties>
	<alibaba.fastjson.version>1.2.75</alibaba.fastjson.version>
	<projecglombok.version>1.18.18</projecglombok.version>
</properties>


	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>${alibaba.fastjson.version}</version>
	</dependency>
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<version>${projecglombok.version}</version>
	</dependency>

2. 配置文件application.properties

server.port=8010

3. request 请求实体类

import lombok.Data;

@Data
public class StudentRequest {

	private String name;
	private Integer age;
	private String attachmentFolder;
	private String attachmentName;
	private byte[] attachment;
}

4. response 响应实体类

import lombok.Data;

@Data
public class StudentResponse {

	private String result;
	private String message;
}

5. 这个demo也写到了传递文件,这儿记录一个文件工具类

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtil {

	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

	public static void saveFile(byte[] bfile, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists()) {// 判断文件目录是否存在
				dir.mkdirs();
			}
			file = new File(filePath + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bfile);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					logger.error(e1.getMessage(), e1);

				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					logger.error(e1.getMessage(), e1);
				}
			}
		}
	}
}

6. controller 服务提供

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.example.demoB.form.StudentRequest;
import com.example.demoB.form.StudentResponse;
import com.example.demoB.service.utils.FileUtil;

@RestController
@RequestMapping("/api/student")
public class StudentController {

	Logger logger = LoggerFactory.getLogger(StudentController.class);

	@PostMapping("/search")
	public StudentResponse search(@RequestBody StudentRequest request) {
		logger.info("request is {}", JSONObject.toJSONString(request));
		StudentResponse studentResponse = new StudentResponse();
		studentResponse.setResult("success");
		studentResponse.setMessage("wow! success! ");
		return studentResponse;
	}

	@PostMapping(value = "/save")
	public ResponseEntity<StudentResponse> save(@RequestBody StudentRequest studentRequest) {
		StudentResponse studentResponse = new StudentResponse();

		logger.info("student name is {},age is {}", studentRequest.getName(), studentRequest.getAge());
		String filePath = studentRequest.getAttachmentFolder();
		String fileName = studentRequest.getAttachmentName();
		byte[] fileContent = studentRequest.getAttachment();
		FileUtil.saveFile(fileContent, filePath, fileName);

		studentResponse.setResult("success");
		studentResponse.setMessage("wow! success! ");
		return new ResponseEntity<>(studentResponse, HttpStatus.OK);
	}

	@PostMapping(value = "/saveList")
	public ResponseEntity<StudentResponse> save(@RequestBody List<StudentRequest> studentRequests) {
		StudentResponse studentResponse = new StudentResponse();

		for (StudentRequest studentRequest : studentRequests) {
			logger.info("student name is {},age is {}", studentRequest.getName(), studentRequest.getAge());
			String filePath = studentRequest.getAttachmentFolder();
			String fileName = studentRequest.getAttachmentName();
			byte[] fileContent = studentRequest.getAttachment();
			FileUtil.saveFile(fileContent, filePath, fileName);
		}

		studentResponse.setResult("success");
		studentResponse.setMessage("wow! success! ");
		return new ResponseEntity<>(studentResponse, HttpStatus.OK);
	}
}

3. Demo A

1. 添加依赖

<properties>
	<alibaba.fastjson.version>1.2.75</alibaba.fastjson.version>
	<projecglombok.version>1.18.18</projecglombok.version>
	<httpclient.version>4.5.13</httpclient.version>
</properties>


	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>${alibaba.fastjson.version}</version>
	</dependency>
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<version>${projecglombok.version}</version>
	</dependency>
	<dependency>
		<groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpclient</artifactId>
		<version>${httpclient.version}</version>
	</dependency>

2. 配置文件 application.properties

file.folder=C:/test/demoB/

3. request 请求实体类 和 response 响应实体类 和Demo B 项目保持一直

4. FileUtil 工具类

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtil {

	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

	public static byte[] File2byte(File filePath) {
		byte[] buffer = null;

		try {
			FileInputStream fis = new FileInputStream(filePath);

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (IOException e) {
			logger.error("error message {}", e.getMessage());
		}
		return buffer;
	}
}

5. HttpClient 工具类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.example.demoA.DemoAApplication;

public class HttpClientUtil {

	static Logger logger = LoggerFactory.getLogger(DemoAApplication.class);

	public static String doPost(String url, String data) {
		String line = null;

		// (1) 创建HttpGet实例
		HttpPost post = new HttpPost(url);

		// (2) 设置请求体
		StringEntity myEntity = new StringEntity(data, ContentType.APPLICATION_JSON);
		post.setEntity(myEntity);

		// (3) 使用HttpClient发送get请求,获得返回结果HttpResponse
		CloseableHttpClient client = HttpClients.createDefault();

		try {
			HttpResponse response = client.execute(post);
			// (4) 读取返回结果
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream in = entity.getContent();

				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				line = reader.readLine();
				reader.close();
			}
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}

		return line;
	}
}

6. 调用Demo B 提供的服务

package com.example.demoA.controller;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.example.demoA.utils.FileUtil;
import com.example.demoA.utils.HttpClientUtil;
import com.example.demoB.form.StudentRequest;
import com.example.demoB.form.StudentResponse;

@RestController
@RequestMapping("/api/student")
public class StudentController {

	@Value("${file.folder}")
	private String fileFolder;

	Logger logger = LoggerFactory.getLogger(StudentController.class);

	@GetMapping("/search")
	public void search() {

		// 请求参数
		StudentRequest request = new StudentRequest();
		request.setName("xiaoming");
		request.setAge(22);
		String requestString = JSONObject.toJSONString(request);
		// 请求url
		String serviceUrl = getUrl() + "/api/student/search";
		// 执行请求
		String responseMessage = HttpClientUtil.doPost(serviceUrl, requestString);
		// 请求返回
		StudentResponse studentResponse = JSONObject.parseObject(responseMessage, StudentResponse.class);
		logger.info("studentResponse is {}", JSONObject.toJSONString(studentResponse));

	}

	@GetMapping("/save")
	public void save() {

		// 请求参数
		StudentRequest request = new StudentRequest();
		request.setName("xiaoming");
		request.setAge(22);
		request.setAttachmentName("test.xls");
		request.setAttachmentFolder(fileFolder);
		byte[] fileByte = FileUtil.File2byte(new File("C:\\\\test\\\\demoA\\\\test.xls"));
		request.setAttachment(fileByte);
		String requestString = JSONObject.toJSONString(request);
		// 请求url
		String serviceUrl = getUrl() + "/api/student/save";
		// 执行请求
		String responseMessage = HttpClientUtil.doPost(serviceUrl, requestString);
		// 请求返回
		StudentResponse studentResponse = JSONObject.parseObject(responseMessage, StudentResponse.class);
		logger.info("studentResponse is {}", JSONObject.toJSONString(studentResponse));

	}

	@GetMapping("/saveList")
	public void saveList() {

		// 请求参数
		List<StudentRequest> studentRequests = new ArrayList<StudentRequest>();

		StudentRequest studentRequest1 = new StudentRequest();
		studentRequest1.setName("Melody");
		studentRequest1.setAge(22);
		studentRequest1.setAttachmentName("test1.xls");
		studentRequest1.setAttachmentFolder(fileFolder);
		byte[] fileByte = FileUtil.File2byte(new File("C:\\\\test\\\\demoA\\\\test1.xls"));
		studentRequest1.setAttachment(fileByte);
		studentRequests.add(studentRequest1);

		StudentRequest studentRequest2 = new StudentRequest();
		studentRequest2.setName("Sara");
		studentRequest2.setAge(21);
		studentRequest2.setAttachmentName("test2.xls");
		studentRequest2.setAttachmentFolder(fileFolder);
		byte[] fileByte2 = FileUtil.File2byte(new File("C:\\\\test\\\\demoA\\\\test2.xls"));
		studentRequest2.setAttachment(fileByte2);
		studentRequests.add(studentRequest2);

		String requestString = JSONObject.toJSONString(studentRequests);
		// 请求url
		String serviceUrl = getUrl() + "/api/student/saveList";
		// 执行请求
		String responseMessage = HttpClientUtil.doPost(serviceUrl, requestString);
		// 请求返回
		StudentResponse studentResponse = JSONObject.parseObject(responseMessage, StudentResponse.class);
		logger.info("studentResponse is {}", JSONObject.toJSONString(studentResponse));

	}

	private String getUrl() {
		return "http://localhost:8010";
	}
}

测试: 启动两个项目

分别执行Demo A 的三个方法, 前提保证待传输的文件存在

以上是关于httpcomponents.httpclient 使用的主要内容,如果未能解决你的问题,请参考以下文章

HttpComponents HttpClient连接池-结构

org.apache.httpcomponents.httpclient

org.apache.httpcomponents:httpclient 工具类

httpcomponents.httpclient 使用

org.apache.httpcomponents httpclient 发起HTTP JSON请求

Apache HttpComponents HttpClient 5.0 - Kerberos SPNEGO 客户端