Java调用第三方接口(get/post)

新建maven工程,在pom.xml中导入httpclient与fastjson包,httpclient用来请求,fastjson进行参数转换与处理数据。

主方法

SHA1算法加密

POST 方法

利用 HttpClientBuilder创建连接对象

public static String postMethod(String url, JSONObject json){
    try {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        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);
        int statusCode = response.getStatusLine().getStatusCode();
        if (HttpStatus.SC_OK == statusCode){
            //返回String
            String res = EntityUtils.toString(response.getEntity());
            System.out.println(res);
            return res;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

GET方法 

利用 HttpClientBuilder创建连接对象

public static String getMethod(String url){
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet(url);
    try{
        //这里可以设置请求参数,token等
        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){//根据状态码处理
            //返回字符串
            String res = EntityUtils.toString(response.getEntity());
            System.out.println(res);
            return res;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

参数处理与解析数据

获得的响应参数可以使用json‘进行分析,[ ]为数组,{ }为对象,利用 JSONObject.parseObject(String text)将字符串转为json对象,调用getJSONArray(key)获取json数组JSONArray,getString(key)获取对应的值,getJSONObject()获取json对象。可以根据json结构层层解析,获取需要的数据。
新建json对象,调用put方法可以赋值,之后作为请求参数设置。

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值