文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java调用第三方http接口的方式总结(四种)

2023-08-16 15:06

关注

在实际开发过程中,我们经常需要调用对方提供的接口或测试自己写的接口是否合适。很多项目都会封装规定好本身项目的接口规范,所以大多数需要去调用对方提供的接口或第三方接口(短信、天气等)

①通过JDK网络类Java.net.HttpURLConnection;

②通过common封装好的HttpClient;

③通过Apache封装好的CloseableHttpClient;

④通过SpringBoot-RestTemplate;

一、通过SpringBoot-RestTemplate方式(其余几种的集大成者)

目前可以采用的调用第三方接口有:

1.1、RestTemplateConfig.java类

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.client.ClientHttpRequestFactory;import org.springframework.http.client.SimpleClientHttpRequestFactory;import org.springframework.web.client.RestTemplate; @Configurationpublic class RestTemplateConfig {     @Bean    public RestTemplate restTemplate(ClientHttpRequestFactory factory){        return new RestTemplate(factory);    }     @Bean    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();        factory.setConnectTimeout(15000);        factory.setReadTimeout(5000);        return factory;    }}

1.2、然后在Service类(RestTemplateToInterface )中注入使用

import com.alibaba.fastjson.JSONObject;import com.swordfall.model.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.*;import org.springframework.stereotype.Service;import org.springframework.web.client.RestTemplate; @Servicepublic class RestTemplateToInterface {     @Autowired    private RestTemplate restTemplate;         public User doGetWith1(String url){        ResponseEntity responseEntity = restTemplate.getForEntity(url, User.class);        User user = responseEntity.getBody();        return user;    }         public User doGetWith2(String url){        User user  = restTemplate.getForObject(url, User.class);        return user;    }         public String doPostWith1(String url){        User user = new User("小白", 20);        ResponseEntity responseEntity = restTemplate.postForEntity(url, user, String.class);        String body = responseEntity.getBody();        return body;    }         public String doPostWith2(String url){        User user = new User("小白", 20);        String body = restTemplate.postForObject(url, user, String.class);        return body;    }         public String doExchange(String url, Integer age, String name){        //header参数        HttpHeaders headers = new HttpHeaders();        String token = "asdfaf2322";        headers.add("authorization", token);        headers.setContentType(MediaType.APPLICATION_JSON);         //放入body中的json参数        JSONObject obj = new JSONObject();        obj.put("age", age);        obj.put("name", name);         //组装        HttpEntity request = new HttpEntity<>(obj, headers);        ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);        String body = responseEntity.getBody();        return body;    }}

二、通过JDK网络类Java.net.HttpURLConnection

比较原始的一种调用做法,这里把get请求和post请求都统一放在一个方法里面

import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class HttpUrlConnectionToInterface {         public static void doPostOrGet(String pathUrl, String data){        OutputStreamWriter out = null;        BufferedReader br = null;        String result = "";        try {            URL url = new URL(pathUrl);            //打开和url之间的连接            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            //请求方式            conn.setRequestMethod("POST");            //conn.setRequestMethod("GET");             //设置通用的请求属性            conn.setRequestProperty("accept", "*            //获取URLConnection对象对应的输出流            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");            //发送请求参数即数据            out.write(data);            //flush输出流的缓冲            out.flush();                         //获取URLConnection对象对应的输入流            InputStream is = conn.getInputStream();            //构造一个字符流缓存            br = new BufferedReader(new InputStreamReader(is));            String str = "";            while ((str = br.readLine()) != null){                result += str;            }            System.out.println(result);            //关闭流            is.close();            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。            conn.disconnect();         } catch (Exception e) {            e.printStackTrace();        }finally {            try {                if (out != null){                    out.close();                }                if (br != null){                    br.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }     public static void main(String[] args) {                doPostOrGet("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");    }}

三、 通过apache common封装好的HttpClient

(1)httpClient的get或post请求方式步骤

  1. 生成一个HttpClient对象并设置相应的参数;
  2. 生成一个GetMethod对象或PostMethod并设置响应的参数;
  3. 用HttpClient生成的对象来执行GetMethod生成的Get方法;
  4. 处理响应状态码;
  5. 若响应正常,处理HTTP响应内容;
  6. 释放连接。

(2)导入如下jar包

                       commons-httpclient            commons-httpclient            3.1        
import com.alibaba.fastjson.JSONObject;import org.apache.commons.httpclient.*;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.params.HttpMethodParams; import java.io.IOException;import java.io.InputStream;public class HttpClientToInterface {         public static String doGet(String url, String charset){                HttpClient httpClient = new HttpClient();        //设置Http连接超时为5秒        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);                 GetMethod getMethod = new GetMethod(url);        //设置get请求超时为5秒        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);        //设置请求重试处理,用的是默认的重试处理:请求三次        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());         String response = "";                 try {            int statusCode = httpClient.executeMethod(getMethod);                         if (statusCode != HttpStatus.SC_OK){                System.err.println("请求出错:" + getMethod.getStatusLine());            }                         //HTTP响应头部信息,这里简单打印            Header[] headers = getMethod.getResponseHeaders();            for (Header h: headers){                System.out.println(h.getName() + "---------------" + h.getValue());            }            //读取HTTP响应内容,这里简单打印网页内容            //读取为字节数组            byte[] responseBody = getMethod.getResponseBody();            response = new String(responseBody, charset);            System.out.println("-----------response:" + response);            //读取为InputStream,在网页内容数据量大时候推荐使用            //InputStream response = getMethod.getResponseBodyAsStream();         } catch (HttpException e) {            //发生致命的异常,可能是协议不对或者返回的内容有问题            System.out.println("请检查输入的URL!");            e.printStackTrace();        } catch (IOException e){            //发生网络异常            System.out.println("发生网络异常!");        }finally {                        getMethod.releaseConnection();        }        return response;    }         public static String doPost(String url, JSONObject json){        HttpClient httpClient = new HttpClient();        PostMethod postMethod = new PostMethod(url);         postMethod.addRequestHeader("accept", "*    public static String doGet(String url, String token){        //创建HttpClient对象        CloseableHttpClient httpClient = HttpClientBuilder.create().build();        HttpGet get = new HttpGet(url);         try {            if (tokenString != null && !tokenString.equals("")){                tokenString = getToken();            }            //api_gateway_auth_token自定义header头,用于token验证使用            get.addHeader("api_gateway_auth_token", tokenString);            get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");            HttpResponse response = httpClient.execute(get);            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){                //返回json格式                String res = EntityUtils.toString(response.getEntity());                return res;            }        } catch (IOException e) {            e.printStackTrace();        }        return null;    }         public static String doPost(String url, JSONObject json){                try {            if (httpClient == null){                httpClient = HttpClientBuilder.create().build();            }             HttpPost post = new HttpPost(url);                        if (tokenString != null && !tokenString.equals("")){                tokenString = getToken();            }                        //api_gateway_auth_token自定义header头,用于token验证使用            post.addHeader("api_gateway_auth_token", tokenString);            post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");             StringEntity s = new StringEntity(json.toString());            s.setContentEncoding("UTF-8");            //发送json数据需要设置contentType            s.setContentType("application/x-www-form-urlencoded");            //设置请求参数            post.setEntity(s);            HttpResponse response = httpClient.execute(post);             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){                //返回json格式                String res = EntityUtils.toString(response.getEntity());                return res;            }        } catch (Exception e) {            e.printStackTrace();        }finally {            if (httpClient != null){                try {                    httpClient.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return null;    }         public static String getToken(){         String token = "";         JSONObject object = new JSONObject();        object.put("appid", "appid");        object.put("secretkey", "secretkey");         try {            if (httpClient == null){                httpClient = HttpClientBuilder.create().build();            }            HttpPost post = new HttpPost("http://localhost/login");                        post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");             StringEntity s = new StringEntity(object.toString());            s.setContentEncoding("UTF-8");            //发送json数据需要设置contentType            s.setContentType("application/x-www-form-urlencoded");            //设置请求参数            post.setEntity(s);            HttpResponse response = httpClient.execute(post);             //这里可以把返回的结果按照自定义的返回数据结果,把string转换成自定义类            //ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class);            //把response转为jsonObject            JSONObject result = JSONObject.parseObject(response);            if (result.containsKey("token")){                token = result.getString("token");            }        } catch (Exception e) {            e.printStackTrace();        }        return token;    }         public static void test(String telephone){         JSONObject object = new JSONObject();        object.put("telephone", telephone);         try {            //首先获取token            tokenString = getToken();            String response = doPost("http://localhost/searchUrl", object);             //如果返回的结果是list形式的,需要使用JSONObject.parseArray转换            //List list = JSONObject.parseArray(response, Result.class);             System.out.println(response);         } catch (Exception e) {            e.printStackTrace();        }    }     public static void main(String[] args) {        test("12345678910");    } }
public static void doPost(String url, String name, String pwd, String phone, String content) {// 创建默认的httpClient实例.CloseableHttpClient httpclient = HttpClients.createDefault();// 创建httppostHttpPost httppost = new HttpPost(url);// 创建参数队列List formparams = new ArrayList();formparams.add(new BasicNameValuePair("account", name));formparams.add(new BasicNameValuePair("passwd", pwd));formparams.add(new BasicNameValuePair("phone", phone));formparams.add(new BasicNameValuePair("content", content));UrlEncodedFormEntity uefEntity;try {uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");httppost.setEntity(uefEntity);System.out.println("executing request " + httppost.getURI());CloseableHttpResponse response = httpclient.execute(httppost);try {HttpEntity entity = response.getEntity();if (entity != null) {System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));}} finally {response.close();}} catch (Exception e) {e.printStackTrace();} finally {// 关闭连接,释放资源try {httpclient.close();} catch (IOException e) {e.printStackTrace();}}}

来源地址:https://blog.csdn.net/qq_43842093/article/details/129292201

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯