核心pom
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.3</version> </dependency>
//json转map public Map JSONandMap(String param){ Map<String,Object> userMap=new HashMap<>(); JSONObject response = JSONObject.parseObject(param); for (Map.Entry<String, Object> entry : response.entrySet()) { userMap.put(entry.getKey(), entry.getValue()); } return userMap; }
//发送post请求的文件上传
public Map addfile(MultipartFile file) { //创建http客户端 CloseableHttpClient httpClient= HttpClientBuilder.create().build(); //接收数据并返回 Map<String,Object> userMap=new HashMap<>(); String resultJson=null; //发送post请求传入地址 HttpPost post=new HttpPost(file_url); //127.0.0.1:8080/xxxx/xxxx try { //上传文件 别的格式参考 httpEntity MultipartEntityBuilder builder=MultipartEntityBuilder.create(); //参数分别为 // files: 入参的键, // file.getInputStream(): 字节输入流 // ContentType.MULTIPART_FORM_DATA: 设置内容类型 //file.getOriginalFilename(): 文件名称 builder.setCharset(Charset.forName("UTF-8")).addBinaryBody ("files", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename()); // HttpEntity entity=builder.build(); post.setEntity(entity); HttpResponse res = httpClient.execute(post); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 返回json格式 resultJson = EntityUtils.toString(res.getEntity()); //JSONandMap 下面封装的JSON 转 map对象 userMap=JSONandMap(resultJson); System.out.println(userMap); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return userMap; }
//发送post json 请求 public Map<String, Object> pythonSF(Map map,String url) throws JsonProcessingException{ String resultJson=null; Map<String,Object> userMap=new HashMap<>(); /*正文*/ CloseableHttpClient httpClient= HttpClientBuilder.create().build(); HttpPost post=new HttpPost(url); String json = objectMapper.writeValueAsString(map); try { //UrlEncodedFormEntity entity=new UrlEncodedFormEntity(json, Consts); StringEntity s = new StringEntity(json); s.setContentEncoding("UTF-8"); s.setContentType("application/json"); post.setEntity(s); HttpResponse res = httpClient.execute(post); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { resultJson = EntityUtils.toString(res.getEntity()); userMap=JSONandMap(resultJson); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return userMap; }