导入Jar包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.4</version>
</dependency>
第一种方式上传文件(httpclient)
public static void main(String[] args) {
try {
String filePath = "C:\\Users\\Dell\\Desktop\\做好的模板\\使用教程.txt";
InputStream is = new FileInputStream(new File(filePath));
String fileName ="aaa";
String uploadURL = "http://localhost:8083/aaa";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uploadURL);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", is, ContentType.DEFAULT_BINARY,fileName);
builder.addTextBody("jsonObject","jsonObject");
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if(responseEntity != null){
String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
System.out.println(result);
}
}catch (Exception ex){
ex.printStackTrace();
}
}
第二种方式上传文件(spring)
public static void ocrDiscern(String jsonObject, String filePath, String riu) {
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("multipart/form-data");
headers.setContentType(type);
FileSystemResource fileSystemResource = new FileSystemResource(filePath);
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("multipartFile", fileSystemResource);
form.add("jsonObject", jsonObject);
form.add("AppId", "2002100");
org.springframework.http.HttpEntity<MultiValueMap<String, Object>> files = new org.springframework.http.HttpEntity<>(form, headers);
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(riu, files, String.class);
System.out.println(result);
}
三.发送JSON数据
public static String callingInterface(String path,Object obj) throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(path);
httpPost.setEntity(new StringEntity(JSON.toJSONString(obj),
ContentType.create("application/json", "UTF-8")));
CloseableHttpResponse execute = httpClient.execute(httpPost);
HttpEntity entity = execute.getEntity();
String str = EntityUtils.toString(entity);
httpPost.clone();
httpClient.close();
System.out.println(str);
return str;
}