调取第三方http接口的的一系列方法

系列文章目录


第三方是get请求

一、第一种get方法,原始java实现,有参数或者在url中拼接参数

  try {
            URL url = new URL("为第三方get请求的url");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;//直接在ulr中拼接参数了,就不需要发送请求参数  
            conn.setRequestMethod("GET");//此处为大写
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            //如果有参数的话可以像下面这样子写,
            String data="id=10&xxx=0";
			out.print(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }

            //关闭流
            is.close();
            //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
            System.out.println("完整结束");
        } catch (Exception e) {
            e.printStackTrace();
        }

二、第二种get方法,,无参数或者在url中拼接参数

     String token=appidLoginService.getToken();
        String url="为第三方get请求的url";
        JSONObject postData = new JSONObject();
        HttpHeaders headers = new HttpHeaders();
        headers.add("token", token);//有就加没有就不加
        HttpEntity<Object> httpEntity = new HttpEntity<Object>(postData, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> exchange = restTemplate.exchange(
                url,//获取资源的地址
                HttpMethod.GET,
                httpEntity,
                String.class);//返回类型设为String)

该处使用的url网络请求的数据。


第三方是Post请求

一、就直接用restTemplat工具类来调用post接口 第三方接口中用from-data方式入参


        String url="http://xxxx";
        MultiValueMap<String, String> postData= new LinkedMultiValueMap<>();
        postData.put("typeValue", Collections.singletonList("xh"));
        postData.put("num", Collections.singletonList("10"));
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, String>> requestParams = new HttpEntity<>(postData, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> exchange = restTemplate.exchange(
                url,//获取资源的地址
                HttpMethod.POST,
                requestParams,
                String.class);//返回类型设为String)
        System.out.println(exchange);

二、第二种Post方法,就直接用restTemplat工具类来调用post接口 第三方接口中用json方式入参(与上面略微不同, restTemplate.postForEntity中这个方法也行)

     String url="http://xxxx";
        JSONObject postData = new JSONObject();
        postData.put("xxx", "xxxxx");
        postData.put("xxx", "xxxxx");
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Object> httpEntity = new HttpEntity<Object>(postData, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> jsonObjectResponseEntity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
        AppidLogin appidLogin = JSONObject.parseObject(jsonObjectResponseEntity.toString(), AppidLogin.class);

传参为图片的第三方调用

一、HttpClients传MultipartFile file

try {
	CloseableHttpClient httpClient = HttpClients.createDefault();
	String httpUrl="http://xxx"
	 HttpPost httpPost = new HttpPost(httpUrl);
	 //builder.setCharset(Charset.forName("UTF-8"));//此处踩坑,转发出去的filename依旧是乱码
	 //ContentType.create("multipart/form-data",Charset.forName("UTF-8"))//此处也是坑,转发出去的filename依然是乱码
	 //HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
	MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
	String originFileName = null;
	originFileName = file.getOriginalFilename();
	 // 设置上传文件流(需要是输出流),设置contentType的类型
	 builder.addBinaryBody("file", file.getBytes(), ContentType.MULTIPART_FORM_DATA, originFileName);
	 //post请求中的其他参数
	 HttpEntity entity = builder.build();
	 httpPost.setEntity(entity);
	 // 执行提交
	 HttpResponse response = httpClient.execute(httpPost);
	 //接收调用外部接口返回的内容
	 HttpEntity responseEntity = response.getEntity();
	
	
	//解析返回出来的内容
	BufferedReader in = null;
	StringBuilder result = new StringBuilder();
	 if (response.getStatusLine().getStatusCode() == 200){
	     //响应内容都存在content中
	       InputStream content = responseEntity.getContent();
	       in = new BufferedReader(
	               new InputStreamReader(content));
	       String line;
	       while ((line = in.readLine()) != null) {
	           result.append(line);
	       }
	   }
   } catch (Exception e) {
           e.printStackTrace();
       }finally {//处理结束后关闭httpclient的链接
           try {
               httpClient.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }

System.out.println(result.toString());

二、restTemplate上传文件—上传的文件是File类型

//如果文件保存在本地,即可以通过File file = new File(path) 或者 文件路径地址获取到指定文件
//这种方式可直接将File文件或者文件路径传递给FileSystemResource资源对象。然后将该资源放入请求体中。


public void uploadFile(File file) {
    // 1、封装请求头
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("multipart/form-data");
    headers.setContentType(type);
    headers.setContentLength(file.length());
    headers.setContentDispositionFormData("media", file.getName());
    // 2、封装请求体
    MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
    FileSystemResource resource = new FileSystemResource(file);
    param.add("file", resource);
    // 3、封装整个请求报文
    HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(param, headers);
    // 4、发送请求
    ResponseEntity<String> data = restTemplate.postForEntity(tempMaterialUploadUrl, formEntity, String.class);
    // 5、请求结果处理
    JSONObject weChatResult = JSONObject.parseObject(data.getBody());

三、上传的文件是InputStream流


如果文件不存在本地,而是在阿里云OSS或者其他只能够通过URL获取文件流,并且不想将文件存到本地而直接通过restTemplate发送,则可以使用下面方式。

例子:在工作中用到这个例子:我将系统上传的附件通过阿里云API上传至阿里云OSS,紧接着要讲文件存到企业微信服务器,而且系统服务器不存储任何附件,就用到了下面的方式,通过阿里云API将上传的附件A通过InputStream形式获取到,然后向企业微信服务端上传该输入流即可。

在需要输入流进行上传文件时,需要使用InputStreamResource构建资源文件,注意要重写contentLength()getFilename()方法,否则不成功。至于参数中的fileName和contentLength要提前通过文件的URL获取到,因为我是从阿里云OSS读取的文件,所以直接能够获取到文件的大小和文件名。

public String uploadInputStream(InputStream inputStream,String fileName,long cententLength) {
    // 1、封装请求头
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("multipart/form-data");
    headers.setContentType(type);
    headers.setContentDispositionFormData("media", fileName);
    // 2、封装请求体
    MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
    InputStreamResource resource = new InputStreamResource(inputStream){
        @Override
        public long contentLength(){
            return cententLength;
        }
        @Override
        public String getFilename(){
            return fileName;
        }
    };
    param.add("file", resource);
    // 3、封装整个请求报文
    HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(param, headers);
    // 4、发送请求
    ResponseEntity<String> data = restTemplate.postForEntity(tempMaterialUploadUrl, formEntity, String.class);
    // 5、请求结果处理
    JSONObject weChatResult = JSONObject.parseObject(data.getBody());
    // 6、返回结果
    return weChatResult;
}


四、上传的是MultipartFile类型文件

注意点:使用ByteArrayResource构建资源时,应重写ByteArrayResource的getFilename()方法,不然不成功。


public String uploadFileWithInputStream(MultipartFile file) throws IOException {
    // 1、封装请求头
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("multipart/form-data");
    headers.setContentType(type);
    headers.setContentLength(file.getSize());
    headers.setContentDispositionFormData("media", file.getOriginalFilename());
    // 2、封装请求体
    MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
    // 将multipartFile转换成byte资源进行传输
    ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
        @Override
        public String getFilename() {
            return file.getOriginalFilename();
        }
    };
    param.add("file", resource);
    // 3、封装整个请求报文
    HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(param, headers);
    // 4、发送请求
    ResponseEntity<String> data = restTemplate.postForEntity(tempMaterialUploadUrl, formEntity, String.class);
    // 5、请求结果处理
    JSONObject weChatResult = JSONObject.parseObject(data.getBody());
    // 6、返回结果
    return weChatResult;
}
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值