最近在做一個項目,需要頻繁的調用第三方的接口,本以爲都是基本的數據類型,沒想到需要傳一個文件類型的參數,我想着調用接口的時候直接用文件流把文件寫到connection不就行了,這就是我一開始寫的調用工具類
public static String sendGetFile(String url, MultipartFile file) {
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection connection = realUrl.openConnection();
// 設置通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連接
connection.connect();
// 獲取所有響應頭字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應頭字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送GET請求出現異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
沒想到報了文件損壞錯誤,改方法無用,改用form-data方式來傳數據方法如下
public static String sendGetFile(String url, String filePath) {
String sResponse="";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
File f = new File(filePath);
// 把文件加到HTTP的post請求中
builder.addBinaryBody(
"code_file",
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
sResponse = EntityUtils.toString(responseEntity, "UTF-8");
}catch (Exception e){
e.printStackTrace();
}
return sResponse;
}
結果成功!