使用Java调用第三方接口并将数据JSON格式化

先创建一个工具类,方便我们调用然后

package com.ninestars.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * CREATE BY Chaiyz ON 2022.04.12 14:23 星期二
 * DESC:
 */
public class HttpClientUtil {
    private int connectionRequestTimeout = 10000;
    private int connectTimeout = 10000;
    private int socketTimeout = 10000;
    private String urlHead="";//接口头部

    //post
    public String sendPostMap(String postUrl, Map<String, Object> params,String type) throws Exception {
        //type
        // 1接收用@responsebody
        // 2接收用@requestparam或者httpservletrequest.getParameter

        //CloseableHttpClient httpClient = createSSLClientDefault();//https
        CloseableHttpClient httpClient = HttpClients.createDefault();//http

        try {
            //实例化post方法
            HttpPost httpost = new HttpPost(urlHead+postUrl);
            config(httpost);
            //提交参数

            if("1".equals(type)){
                String ms = String.valueOf(params);
                StringEntity stringEntity = new StringEntity(String.valueOf(params),"UTF-8");
                stringEntity.setContentType("application/json");

                //将参数给post方法
                httpost.setEntity(stringEntity);
            }else{
                List<NameValuePair> nvps = new ArrayList<>();
                if(params != null){
                    Set<String> keySet = params.keySet();
                    for(String key:keySet){
                        nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
                    }
                }
                UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps,"UTF-8");
                uefEntity.setContentType("application/x-www-form-urlencoded");
                //将参数给post方法
                httpost.setEntity(uefEntity);
            }

            //执行post方法
            CloseableHttpResponse response = httpClient.execute(httpost, HttpClientContext.create());
            //获取返回值
            HttpEntity entity = response.getEntity();
            String reponseStr = EntityUtils.toString(entity, "utf-8");
            return reponseStr;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    //get
    public String sendGetMap(String postUrl, Map<String, Object> params) throws Exception
    {
        //CloseableHttpClient httpClient = createSSLClientDefault();//https
        CloseableHttpClient httpClient = HttpClients.createDefault();//http
        try {

            //提交参数
            List<NameValuePair> nvps = new ArrayList<>();
            if(params != null){
                Set<String> keySet = params.keySet();
                for(String key:keySet){
                    nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
            }

            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps,"UTF-8");
            uefEntity.setContentType("application/x-www-form-urlencoded");
            //将参数给get方法
            String sparam = EntityUtils.toString(uefEntity);
            //实例化get方法
            HttpGet httget = new HttpGet(urlHead+postUrl+"?"+sparam);
            config(httget);

            //执行get方法
            CloseableHttpResponse response = httpClient.execute(httget);
            //获取返回值
            HttpEntity entity = response.getEntity();
            String reponseStr = EntityUtils.toString(entity, "utf-8");
            return reponseStr;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * @param httpRequestBase
     */
    private void config(HttpRequestBase httpRequestBase) {
        httpRequestBase.setHeader("User-Agent", "Mozilla/5.0");
        httpRequestBase.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpRequestBase.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");//"en-US,en;q=0.5");
        httpRequestBase.setHeader("Accept-Charset", "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7");
        httpRequestBase.setHeader("connection", "Keep-Alive");
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .setConnectTimeout(connectTimeout)
                .setSocketTimeout(socketTimeout)
                .build();
        httpRequestBase.setConfig(requestConfig);
    }


    public JSONObject sendPostForm(String url, Map<String, Object> reqObj, String type) {
        //type
        // 1接收用@requestbody
        // 2接收用@requestparam或者httpservletrequest.getParameter
        try {
            String str = sendPostMap(url, reqObj, type);
            return JSONObject.parseObject(str);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public JSONObject sendGetForm(String url, Map<String, Object> reqObj) {
        try {
            String str = sendGetMap(url, reqObj);
            return JSONObject.parseObject(str);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

 然后我们就可以调用第三方接口了,没错。就是这么简单。看我演示

  String url = "http://**/*/*"; //这里是你要调用的接口地址
        Map<String, Object> reqObj = new HashMap<>();// 这里是你要传的参数
        reqObj.put("terminalCode","CCBBAA0123456789");
        reqObj.put("magazineUpdateTime","2010-01-01 00:00:00");
        reqObj.put("cpage",1);
        reqObj.put("pageSize",10);
        reqObj.put("details",1);
        JSONObject jsonObject = httpClientUtil.sendPostForm(url, reqObj,"2");
        return jsonObject;// 现在就拿到接口的返回值了。

创作不易,如果有用记得点赞哦!

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java调用第三方接口一般有以下几种方式: 1. 使用Java自带的URLConnection或者HttpClient等HTTP客户端库进行访问,获得接口返回的数据,然后进行解析处理。 示例代码: ```java URL url = new URL("http://example.com/api"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); int status = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer content = new StringBuffer(); while ((inputLine = in.readLine()) != null) { content.append(inputLine); } in.close(); con.disconnect(); // 处理返回的数据 String response = content.toString(); ``` 2. 使用第三方HTTP客户端库,比如Apache HttpComponents或者OkHttp等,这些库提供了更加方便易用的API。 示例代码: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet request = new HttpGet("http://example.com/api"); HttpResponse response = httpClient.execute(request); // 处理返回的数据 String result = EntityUtils.toString(response.getEntity()); ``` 3. 使用Spring的RestTemplate,它提供了一种更加高级的HTTP客户端API,可以更加方便地进行JSON/XML数据的序列化和反序列化。 示例代码: ```java RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject("http://example.com/api", String.class); // 处理返回的数据 ``` 以上是Java调用第三方接口的基本方式,具体的实现方式可以根据具体的项目需求进行选择。在获取接口返回的数据后,需要根据接口返回的数据格式进行解析处理,比如JSON格式的数据可以使用Jackson或者Gson等库进行解析,XML格式的数据可以使用JAXB等库进行解析。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值