坑:java後端模擬表單提交,上傳文件至第三方API

一、需求

上傳圖片,調用API,獲取人臉識別特徵值

二、錯誤

1、首先,我使用了這些工具類,都能調用成功,但是無法返回數據,說明傳輸的參數不對,參考了網上的各種方法,都不行。

列舉下使用的工具類:
1、java.net.HttpURLConnection
2、org.apache.commons.httpclient
3、org.apache.http.client.methods.HttpPost

三、postMan調用

1、首先header的Content-Type選擇multipart/form-data

2、選擇body,我傳輸的key叫“img”,選擇“File”,選中待上傳圖片

3、調用成功,返回人臉特徵結果

四、從postMan獲取java代碼

1、選中右上角【code】

2、選中java-Okhttp

3、複製代碼至工程中,添加pom

    <dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.9</version>
</dependency>

注意:版本需要3.X版本,4.X版本使用postman的代碼會報錯。

4、最終代碼

/**
* 使用okHttp3上傳img
* @param url
* @param imgPath
* @return
*/

public static String uploadImg(String url, String imgParam, String imgPath) {
OkHttpClient client = new OkHttpClient().newBuilder().build();
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart(imgParam,imgPath,
RequestBody.create(MediaType.parse("application/octet-stream"),
new File(imgPath)))
.build();
Request request = new Request.Builder()
.url(url)
.method("POST", body)
.addHeader("Content-Type", "multipart/form-data")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
logger.error("uploadFile error ,pathUrl:[{}],error:[{}]",url,e);
return "";
}
try {
return response.body().string();
} catch (IOException e) {
return "";
}
}

5、方法調用

 public static void main(String[] args) throws Exception {


String url = "http://XXX";
String imgParam = "img";
String imgPath = "C:\\Users\\Administrator\\Pictures\\人臉\\testface1.jpg";
String result = uploadImg(url,imgParam,imgPath);
System.out.println( result );
}

6、輸出結果


本文分享自微信公衆號 - 架構師之殤(ysistrue)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章