private static String uploadFile(File file, String url) {
CloseableHttpClient httpClient = null;
String result = "";
try {
httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
RequestConfig config = RequestConfig
.custom()
.setConnectTimeout(200000)
.setConnectionRequestTimeout(200000)
.setSocketTimeout(200000)
.build();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("image_file", file);
post.setEntity(builder.build());
post.setConfig(config);
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "UTF-8");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("返回结果:" + result);
return result;
}