一、前言
虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
注意: HttpClient有两种形式,一种是org.apache.http下的,一种是org.apache.commons.httpclient.HttpClient。
二、客户端处理
package TestZookeeper.TestZookeeper;
import java.io.File;
import java.io.FileInputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* 发送请求
* @author lindm
* @date 2018/11/30
*/
public class App
{
public static void main(String[] args) {
@SuppressWarnings("deprecation")
HttpClient ht = new DefaultHttpClient();
HttpPost post = new HttpPost("http://127.0.0.1:8088/egovAtt/uploadEgovAttFile");
HttpResponse rs = null;
try{
File testFile = new File("C:/Users/Administrator/Documents/Tencent Files/594485991/FileRecv/MobileFile/(批注)(9).pdf");
System.out.println(testFile.exists());
//文件流包装到FileBody
post.setEntity(new InputStreamEntity(new FileInputStream(testFile),testFile.length()));
//设置请求内容类型(若不显示设置,默认text/plain;不同的类型服务端解析格式不同,可能导致参请求参数解析不到的情况)
post.addHeader("Content-Type", "application/octet-stream");
//设置请求参数docId
post.addHeader("docId", "W86GOuSwhwKc1xGG"); post.addHeader("type", "pdf");
//发送请求
rs = ht.execute(post);
System.out.println(""+rs.getStatusLine().getStatusCode()+" "+EntityUtils.toString(rs.getEntity(),"utf-8"));
}catch (Exception e) {
e.printStackTrace();
}finally{
// 销毁
EntityUtils.consume(rs);
}
}
}
三、服务端处理
/**
* 上传附件,单文件上传<br/>
* <ul>
* <li>请求头需携带参数:docId(所属文档id)、type(附件类别)、contentType(文件类型)
* 、fileName(附件名称)、Content-Type(文件类型)</li>
* </ul>
*
* @return
*/
@PostMapping("/uploadEgovAttFileWithFileStream")
public @ResponseBody String uploadEgovAttFileWithFileStream(HttpServletRequest request) throws Exception {
//从请求头获取参数
String docId = request.getHeader("docId");
String type = request.getHeader("type");
String extension = request.getHeader("extension");
String fileName = request.getHeader("fileName");
// 读取文件流
InputStream is = request.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
is.close();
// 转为字节数组
byte[] fileByte = baos.toByteArray();
//...do anything
return "upload success";
}
四、参考博文
1、https://www.cnblogs.com/Scott007/p/3817285.html
2、https://www.cnblogs.com/wuweidong/p/5953167.html
3、https://www.jianshu.com/p/7ab966dfa507
网友评论