一、前言
雖然在 JDK 的 java.net 包中已經(jīng)提供了訪問 HTTP 協(xié)議的基本功能谅年,但是對(duì)于大部分應(yīng)用程序來說谈秫,JDK 庫本身提供的功能還不夠豐富和靈活。HttpClient 用來提供高效的瞧甩、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包弥鹦,并且它支持 HTTP 協(xié)議最新的版本和建議肚逸。
注意: 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;
/**
* 發(fā)送請(qǐng)求
* @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()));
//設(shè)置請(qǐng)求內(nèi)容類型(若不顯示設(shè)置务冕,默認(rèn)text/plain;不同的類型服務(wù)端解析格式不同血当,可能導(dǎo)致參請(qǐng)求參數(shù)解析不到的情況)
post.addHeader("Content-Type", "application/octet-stream");
//設(shè)置請(qǐng)求參數(shù)docId
post.addHeader("docId", "W86GOuSwhwKc1xGG"); post.addHeader("type", "pdf");
//發(fā)送請(qǐng)求
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);
}
}
}
三、服務(wù)端處理
/**
* 上傳附件洒疚,單文件上傳<br/>
* <ul>
* <li>請(qǐng)求頭需攜帶參數(shù):docId(所屬文檔id)歹颓、type(附件類別)坯屿、contentType(文件類型)
* 油湖、fileName(附件名稱)、Content-Type(文件類型)</li>
* </ul>
*
* @return
*/
@PostMapping("/uploadEgovAttFileWithFileStream")
public @ResponseBody String uploadEgovAttFileWithFileStream(HttpServletRequest request) throws Exception {
//從請(qǐng)求頭獲取參數(shù)
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();
// 轉(zhuǎn)為字節(jié)數(shù)組
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吠昭、http://www.reibang.com/p/7ab966dfa507