Java 调用Restful API接口的几种方式

背景:在开发中常常会遇到调用别人提供的Restful API接口、获取写一个程序去测试Restful API接口的需求,java调用Restful API接口的方式不同于前端Ajax调用,能够实现的方式有很多,这里选用最常用的一种HttpClient。

 HTTPSClient.java 

HttpClient可以远程调用比如请求一个URL,然后在response里获取到返回状态和返回信息,我们就是使用HttpClient进行接口调用,另一个需要注意的知识点是HTTPS,这个牵涉到证书或用户认证的问题。

package cn.itcast.ssm.rest;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
 
public abstract class HTTPSClient extends HttpClientBuilder {
    private CloseableHttpClient client;
    protected ConnectionSocketFactory connectionSocketFactory;
 
    /**
     * 初始化HTTPSClient
     * 
     * @return 返回当前实例
     * @throws Exception
     */
    public CloseableHttpClient init() throws Exception {
        this.prepareCertificate();
        this.regist();
 
        return this.client;
    }
 
    /**
     * 准备证书验证
     * 
     * @throws Exception
     */
    public abstract void prepareCertificate() throws Exception;
 
    /**
     * 注册协议和端口, 此方法也可以被子类重写
     */
    protected void regist() {
        // 设置协议http和https对应的处理socket链接工厂的对象
        Registry socketFactoryRegistry = RegistryBuilder.create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", this.connectionSocketFactory)
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);
 
        // 创建自定义的httpclient对象
        this.client = HttpClients.custom().setConnectionManager(connManager).build();
        // CloseableHttpClient client = HttpClients.createDefault();
    }
}

HTTPSTrustClient.java

继承HTTPSClient,返回一个需要认证的socket。

package cn.itcast.ssm.rest;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
 
public class HTTPSTrustClient extends HTTPSClient {
 
    public HTTPSTrustClient() {
 
    }
 
    @Override
    public void prepareCertificate() throws Exception {
        // 跳过证书验证
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
 
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
 
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        // 设置成已信任的证书
        ctx.init(null, new TrustManager[] { tm }, null);
        this.connectionSocketFactory = new SSLConnectionSocketFactory(ctx);
    }
}

HTTPSClientUtil.java

创建工具类,用于设置参数,这里有两种参数方式,一种是Map格式的参数,一种是Json格式的参数

package cn.itcast.ssm.rest;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
 
public class HTTPSClientUtil {
    private static final String DEFAULT_CHARSET = "UTF-8";
    
    //Map类型的参数
    public static String doPost(HttpClient httpClient, String url, Map paramHeader,
            Map paramBody) throws Exception {
        return doPost(httpClient, url, paramHeader, paramBody, DEFAULT_CHARSET);
    }
 
    public static String doPost(HttpClient httpClient, String url, Map paramHeader,
            Map paramBody, String charset) throws Exception {
 
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        setHeader(httpPost, paramHeader);
        setBody(httpPost, paramBody, charset);
 
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, charset);
            }
        }
 
        return result;
    }
    //json类型的参数
    public static String doPostJson(HttpClient httpClient, String url,String strJson) throws Exception {
        return doPostJson(httpClient, url, strJson, DEFAULT_CHARSET);
    }
    public static String doPostJson(HttpClient httpClient, String url, String strJson, String charset) throws Exception {
 
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        //httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json"); 
        StringEntity entity = new StringEntity(strJson);
        httpPost.setEntity(entity);
 
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, charset);
            }
        }
 
        return result;
    }
    
    public static String doGet(HttpClient httpClient, String url, Map paramHeader,
            Map paramBody) throws Exception {
        return doGet(httpClient, url, paramHeader, paramBody, DEFAULT_CHARSET);
    }
 
    public static String doGet(HttpClient httpClient, String url, Map paramHeader,
            Map paramBody, String charset) throws Exception {
 
        String result = null;
        HttpGet httpGet = new HttpGet(url);
        setHeader(httpGet, paramHeader);
 
        HttpResponse response = httpClient.execute(httpGet);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, charset);
            }
        }
 
        return result;
    }
 
    private static void setHeader(HttpRequestBase request, Map paramHeader) {
        // 设置Header
        if (paramHeader != null) {
            Set keySet = paramHeader.keySet();
            for (String key : keySet) {
                request.addHeader(key, paramHeader.get(key));
            }
        }
    }
 
    private static void setBody(HttpPost httpPost, Map paramBody, String charset) throws Exception {
        // 设置参数
        if (paramBody != null) {
            List list = new ArrayList();
            Set keySet = paramBody.keySet();
            for (String key : keySet) {
                list.add(new BasicNameValuePair(key, paramBody.get(key)));
            }
 
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }
        }
    }
}

HTTPSClientTest.java

进行测试

package cn.itcast.ssm.rest;
 
import java.util.HashMap;
import java.util.Map;
 
import org.apache.http.client.HttpClient;

import com.google.gson.Gson;

import cn.itcast.ssm.po.Gree;
/**
 * https://blog.csdn.net/zpf336/article/details/73480810/
 * @author 738232
 *
 */
public class HTTPSClientTest {
 
    public static void main(String[] args) throws Exception {
        HttpClient httpClient = null;
 
        httpClient = new HTTPSTrustClient().init();
        //httpClient = new HTTPSCertifiedClient().init();
 
        String url = "https://...";
        //String url = "https://1.2.6.2:8011/xxx/api/getHealth";
 
        String AppID = "";
		String Secret = "";
		Gree gree = new Gree();
		gree.setAppID(AppID);
		gree.setSecret(Secret);
		Gson gson=new Gson();  //对象转Json
		String strJson = gson.toJson(gree);
        
        String result = HTTPSClientUtil.doPostJson(httpClient, url, strJson);
        
        //String result = HTTPSClientUtil.doGet(httpsClient, url, null, null);
        
        System.out.println(result);
    }
 
}

博客文章同步在微信公众号:Web小项目

覆盖百万优质粉丝的web项目分享平台;

优质Web项目分享,技术解决方案汇总,开发资料分享,面试资料汇总,互联网公司面试真题,技术博客等专题内容;

扫描下方二维码关注我们,领取项目资料:

Java 调用Restful API接口的几种方式_第1张图片

你可能感兴趣的:(JavaEE,常用小功能)