Java 代码中如何调用 第三方Api

在代码中调用第三方API 获取数据

 

package com.example.demo.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.utils.URIBuilder;
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.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 提供调用第三方API 的 get与 post 接口
 * Created by baizhuang on 2019/9/12 11:37.
 */

@Slf4j
public class HttpClient {
    /**
     * 表单格式传输
     */
    private static final String FORM_CONTEXT_TYPE ="application/x-www-form-urlencoded";

    /**
     * json 默认的编码类型
     */
    private static final  String JSON_CONTENT_TYPE = "application/json";

    /**
     * 默认的编码格式
     */
    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 请求配置对象
     */
    private static RequestConfig requestConfig;

    /**
     *  get 请求,将参数包含在 url 路径中
     *  url : 路径
     *  return: json 对象
     */
    public static JSONObject doGet(String url){
        JSONObject jsonObject = null;
        try(CloseableHttpClient client = HttpClients.createDefault();){
            HttpGet request  = new HttpGet(url);
            request.setConfig(requestConfig);
            try(CloseableHttpResponse response = client.execute(request);){
                int statusCode = response.getStatusLine().getStatusCode();
                if(statusCode == HttpStatus.SC_OK){
                    HttpEntity entity = response.getEntity();
                    String responseContent = EntityUtils.toString(entity);
                    jsonObject = JSONObject.parseObject(responseContent);
                }else{
                    log.info("Get请求失败:{},状态码:{}",url,statusCode);
                }
            }
        }catch (IOException e){
            log.info("Get 请求异常:{},状态码:{}",url,e.getMessage());
            e.printStackTrace();
        }
        return  jsonObject;
    }


    /**
     * get 请求,将参数以Map 的形式传入
     * path : 包括 协议、主机、端口、资源路径
     * param: 请求参数
     *
     * @param
     */
    public static JSONObject doGet(String path,Map<String,String> params){
        List<NameValuePair> queryParans = convertParamsMapToList(params);
        URI uri = null;
        try{
            uri = new URIBuilder()
                    .setPath(path)
                    .setParameters(queryParans)
                    .build();
        }catch (URISyntaxException e){
            e.printStackTrace();
        }
        return doGet(uri.toString());
    }


    /**
     *  将Map<String,String> 类型的请求参数转换为 List<NameValuePair>
     * @param
     *
     */
    private static List<NameValuePair> convertParamsMapToList(Map<String,String> params){
        List<NameValuePair> queryParams  = new ArrayList<>();
        for(String s : params.keySet()){
            queryParams.add(new BasicNameValuePair(s,params.get(s)));
        }
        return  queryParams;
    }

    /**
     * 将请求拆分开传入
     *
     * scheme 请求协议
     * host  主机地址
     * port 端口
     * path 路径
     * params 请求参数
     * @param
     */
    public static JSONObject doGet(String scheme,String host,Integer port,String path,Map<String,String> params){
        List<NameValuePair> queryParams = convertParamsMapToList(params);
        URI uri = null;
        try {
            uri = new URIBuilder().setScheme(scheme)
            .setHost(host)
            .setPort(port)
            .setPath(path)
            .setParameters(queryParams)
            .build();
        }catch (URISyntaxException e){
            e.printStackTrace();
        }
        return  doGet(uri.toString());
    }


    /**
     *  post 请求,请求参数被封装在 JSONObject
     *  url : 请求地址
     *  jsonParam :请求参数
     *
     */
    public static JSONObject doPost(String url,JSONObject jsonParam){
        return doPost(url,jsonParam,null);
    }

    /**
     * doPost ,以表单提交
     */
    public static JSONObject doPost(String url,String params){
        return  doPost(url,params,FORM_CONTEXT_TYPE,null);
    }

    /**
     * post 请求,请求参数被封装在 JSONObject 中,可以设置字符编码
     * url: 请求地址
     * jsonParam : 请求参数
     * charset 字符编码方法
     */
    public static JSONObject doPost(String url,JSONObject jsonParam,String charset){
       return  doPost(url,jsonParam.toJSONString(),JSON_CONTENT_TYPE,charset);
    }



    public static JSONObject doPost(String url,JSONObject jsonParam,boolean isJsonParam,String charset){
        return  doPost(url,jsonParam.toJSONString(),JSON_CONTENT_TYPE,charset);
    }


    /**
     * post 请求,参数为字符串,可以为 JSON ,可以为普通格式,可以设置字符编码
     * 如果为 json 格式, isJsonStringParam = true
     * 如果是普通格式: name  =Jack&age =10 ,则 isJsonStringParam = false
     *
     * url : 请求地址
     * stringParam 请求参数字符串
     * isJsonStringParam : 请求是否为 json 格式
     * charset 字符编码格式
     */
    public static JSONObject doPost(String url,String stringParam,boolean isJsonStringParam,String charset){
        JSONObject jsonResult = null;
        if(isJsonStringParam){
            jsonResult = doPost(url,stringParam,JSON_CONTENT_TYPE,charset);
        }else{
            jsonResult = doPost(url,stringParam,FORM_CONTEXT_TYPE,charset);
        }
        return jsonResult;
    }

    /**
     * Post 请求
     * url: 请求地址
     * requestParam 请求参数,字符串格式
     * contentType 内容编码格式
     * charset 字符编码格式
     *
     */
    public static JSONObject doPost(String url,String requestParam,String contentType,String charset){
        charset = charset==null?DEFAULT_CHARSET:charset;
        JSONObject jsonResult = null;
        try(CloseableHttpClient httpClient = HttpClients.createDefault();){
            HttpPost httpPost = new HttpPost(url);
            //构造实体请求
            StringEntity requestEntity = new StringEntity(requestParam,charset);
            requestEntity.setContentEncoding(charset);
            requestEntity.setContentType(contentType);
            httpPost.setEntity(requestEntity);
            httpPost.setConfig(requestConfig);
            try(CloseableHttpResponse response = httpClient.execute(httpPost);){
                int statusCode = response.getStatusLine().getStatusCode();
                if(statusCode  == HttpStatus.SC_OK){
                    HttpEntity responseEntity  = response.getEntity();
                    String responseContent = EntityUtils.toString(responseEntity,charset);
                    jsonResult = JSONObject.parseObject(responseContent);
                }else{
                    log.error("post 请求失败:{},状态码:{}",url,statusCode);
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return jsonResult;
    }

}

 

转载于:https://www.cnblogs.com/baizhuang/p/11181536.html

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生成调用第三方API代码需要以下步骤: 1. 确认第三方API的使用方式和协议,例如RESTful API、SOAP APIJSON API等。 2. 在Java导入相关的API库或者使用HTTP请求库,例如HttpClient或者OkHttp。 3. 通过API提供的接口文档,构建相应的请求参数、请求头等信息。 4. 发送HTTP请求并获取API返回的响应数据。 5. 解析响应数据并处理异常情况。 下面是一个简单的使用Java调用第三方API的示例代码: ``` import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class ApiCaller { public static void main(String[] args) throws IOException { // 待调用API地址 String apiUrl = "https://api.example.com/some-endpoint"; // 构建HTTP连接 URL url = new URL(apiUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置HTTP请求头 connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Authorization", "Bearer <your-access-token>"); // 发送HTTP请求 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 读取API返回的响应数据 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 处理API返回的响应数据 System.out.println(response.toString()); } else { // 处理API返回的错误信息 System.out.println("API调用失败,错误码为:" + responseCode); } connection.disconnect(); } } ``` 这是一个简单的GET请求示例,实际的调用方式会根据API的不同而有所差异。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值