方法一:使用 org.apache.commons.httpclient;的HttpClient
public Map<String, Object> officialOcrUpload(String filePath) {
Map<String, Object> reContent = new HashMap<>();
String soapResponseInfo = "";
File targeFile = new File(filePath);
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(OFFICIAL_ENDPOINT+"?bizType=tm");
int state = 500;
try {
FilePart filePart = new FilePart(targeFile.getName(), targeFile);
filePart.setContentType("multipart/form-data");
filePart.setName("file");
Part[] parts = {filePart};
postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(Integer.valueOf(OFFICIAL_TIMEOUT));
state = httpClient.executeMethod(postMethod);
if (state == HttpStatus.SC_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream(), "utf-8"));
String responseLine = "";
while((responseLine = bufferedReader.readLine()) != null){
soapResponseInfo += responseLine;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
reContent.put("status", state);
reContent.put("body", soapResponseInfo);
postMethod.releaseConnection();
if (state == HttpStatus.SC_OK) {
reContent = queryOfficalDoc(soapResponseInfo);
}
}
return reContent;
}
方法二:使用org.apache.http.impl.client;的HttpClient
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
public String officialFileUpload(String filepath){
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(OFFICIAL_ENDPOINT+"?bizType=tm");
String result = "";
try {
FileBody bin = new FileBody(new File(filepath));
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.addPart("file", bin);
HttpEntity httpEntity = reqEntity.build();
httpPost.setEntity(httpEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpPost.releaseConnection();
}
return result;
}
目录