专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 技术知识分享,Java接口调用的处理

技术知识分享,Java接口调用的处理

更新时间:2020-05-15 15:52:46 来源:动力节点 浏览1752次

“你调用别人的接口”:

这里提供的方法是POST和GET的方法.

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,我使用的是List<NameValuePair>,采用键值对的形式

4. 释放连接。无论执行方法是否成功,都必须释放连接

来个代码进行讨论把,我会在代码里面进行详细的讲解,这里主要是post和get的方法.

1.先来一个常量类:

/*************************************************接口部分**************************************************/   
    /**
     * 请求正常
     */
    public static final int SUCCESS = 200;
    
    /**
     * 请求参数有误
     */
    public static final int PARAMETER_EXCEPTION = 400;
    
    /**
     * 认证失败
     */
    public static final int AUTHENTICATION_FAILED = 401;
    
    /**
     * 请求地址错误或不存在
     */
    public static final int ADDRESS_EXCEPTION = 404;
    
    /**
     * 请求地址错误或不存在
     */
    public static final int SERVER_EXCEPTION = 500;
    
    /**
     * 接口状态码判断
     */
    public static String putThrowException(int statusCode) {
        String e = "";
        if(PARAMETER_EXCEPTION == statusCode) {
            e = "请求参数有误";
        }else if(AUTHENTICATION_FAILED == statusCode) {
            e = "认证失败";
        }else if(ADDRESS_EXCEPTION == statusCode) {
            e = "请求地址错误或不存在";
        }else if(SERVER_EXCEPTION == statusCode) {
            e = "服务器状态异常";
        }
        return e;
    }    /**
     * Token元素
     */
    public static final String USERNAME = "tianxun";
    public static final String PASSWORD = "123456";
    public static final String token = "dGlhbnh1biUzQTEyMzQ1Ng==";

2.接口类:

package cn.tisson.bycs.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLException;
import org.apache.commons.httpclient.HttpException;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
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.protocol.HttpClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.codec.binary.Base64;

import cn.tisson.bycs.cst.Constants;

/**
 *     接口常用工具类
 * @author zahngrh
 *
 */
public class serviceUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(serviceUtils.class);
    
    /**
     * Base64加密Token
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getBase64() throws UnsupportedEncodingException {
        String str = Constants.USERNAME+":"+Constants.PASSWORD;
        final byte[] textByte = str.getBytes("UTF-8");
        String result= Base64.encodeBase64String(textByte);
        return result;
    }
    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(getBase64());
    }
    
    /**
     * 设置超时重试
     */
    public static HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception,int executionCount,HttpContext context) {
            System.out.println("............................第"+executionCount+"次重试");
        if (executionCount >= 3) {
            return false;
        }else if(exception instanceof UnknownHostException || exception instanceof ConnectTimeoutException
                || !(exception instanceof SSLException) || exception instanceof NoHttpResponseException) {
            return true;
        }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
            //如果请求被认为是等幂,则重试
                return true;
            }
            return false;
        }
    };
    
    /**
     * 接口请求工具类
     */
    public static Map<String,String> requestResult(Map<String,String> map,String putType,String url) throws HttpException, IOException {            
        CloseableHttpResponse response = null;        
        int statusCode = 0; // 状态码      
        String content =""; // 返回结果        
        Map<String,String> resultMap = new HashMap();        
        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();        
        // 设置参数
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();        
        for(String key:map.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key,map.get(key).toString()));
        }        
        String str = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs,Consts.UTF_8));        
        // 设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();
                
        if(putType != null && "post".equals(putType)){            
            // 请求URL地址
            HttpPost httpPost = new HttpPost(url);            
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,Consts.UTF_8));            
            // 设置Token
            httpPost.setHeader("token",Constants.token);           
            httpPost.setConfig(requestConfig);           
            httpClient = HttpClients.custom().setRetryHandler(serviceUtils.myRetryHandler).build();            
            try {
                response = httpClient.execute(httpPost);                
                // 接收状态码
                statusCode = response.getStatusLine().getStatusCode();                
            } catch (Exception e) {
                e.printStackTrace();
            }            
        }else if(putType != null && "get".equals(putType)) {            
            // 请求URL地址
            HttpGet httpGet = new HttpGet(url+"?"+str);
            // 设置Token
            httpGet.setHeader("token",Constants.token);
            httpGet.setConfig(requestConfig);
            httpClient = HttpClients.custom().setRetryHandler(serviceUtils.myRetryHandler).build();
            try {
                response = httpClient.execute(httpGet);
                // 接收状态码
                statusCode = response.getStatusLine().getStatusCode();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        // 判断状态码
        if (Constants.SUCCESS == statusCode) {
            HttpEntity entity = response.getEntity();
            content = EntityUtils.toString(entity, "utf-8");
            logger.info(content);
        } else {
            //logger.error("状态码:"+Constants.putThrowException(statusCode));
        } 
        resultMap.put("statusCode", String.valueOf(statusCode));
        resultMap.put("result", content);
        try {
            // 释放client
            httpClient.close();
        } catch (IOException e) {
            logger.error("http接口调用异常:url is::" + url, e);
        }           
        return resultMap;
    }  
}
对于接口类的调用:

/**
*根据业务使用接口,对返回值进行自我的调整
**/
public static void main(String[] args) throws HttpException, IOException {
        Map<String,String> paraMap = new HashMap();
        paraMap.put("type", "1");
        System.out.println(serviceUtils.requestResult(paraMap, "post", "https://api.apiopen.top/musicRankingsDetails"));
    }

以上就是动力节点java培训机构的小编针对“技术知识分享,Java接口调用的处理”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>