动力节点首页 全国咨询热线:400-8080-105

绑定手机号,登录
手机号

验证码

微信登录
手机号登录
手机号

验证码

微信登录与注册
微信扫码登录与注册

扫码关注微信公众号完成登录与注册
手机号登录
首页 > 文章

Java调用接口之http方式

06-29 11:14 759浏览
举报 T字号
  • 大字
  • 中字
  • 小字

1.http调用类

package com.tbl.common.utils;
import com.alibaba.fastjson.JSON;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map; 
/**
 * http调用共同类
 *
 */
public class HttpUtil {
    //返回数据类型(1:字符串;2:字节数组)
    private static final Integer RETURN_TYPE_STRING = 1; 
    /**
     * http post 方法调用(content-type: application/json)
     * @param url
     * @param params
     * @return 响应数据
     */
    public static String postJSON(String url, String params, Map<String, Object> headers) {
        return (String) postJSONWithResponseHeaders(url, params, headers).get("data");
    } 
    /**
     * 调用指定url返回数据(method: post, content-type: application/json)
     * @param url
     * @param parameters
     * @param headers
     * @return
     */
    public static Map<String, Object> postJSONWithResponseHeaders(String url, String parameters, Map<String, Object> headers) {
        HttpPost httppost = new HttpPost(url);
//        String parameters = JSON.toJSONString(params); 
        if (StringUtils.isEmpty(parameters)) {
            return httpInternelExecute(httppost, headers, RETURN_TYPE_STRING);
        } 
        StringEntity entity = new StringEntity(parameters, ContentType.create("application/json", Consts.UTF_8));
        entity.setChunked(true);
        httppost.setEntity(entity);
        return httpInternelExecute(httppost, headers, RETURN_TYPE_STRING);
    } 
    /**
     * 执行http请求并返回结果
     * @param httpUriRequest
     * @param reqHeaders
     * @param type 返回数据类型(1:字符串;2:字节数组)
     * @return {
     *     responseHeaders:响应头Map
     *     data: 返回结果(String or byte array)
     * }
     */
    private static Map<String, Object> httpInternelExecute(HttpUriRequest httpUriRequest, Map<String, Object> reqHeaders, Integer type) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        BufferedReader reader = null; 
        try {
            if (reqHeaders != null) {
                for (String key : reqHeaders.keySet()) {
                    httpUriRequest.setHeader(key, (String) reqHeaders.get(key));
                }
            }
            response = httpclient.execute(httpUriRequest); 
            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(
                        statusLine.getStatusCode(),
                        statusLine.getReasonPhrase());
            } 
            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            } 
            InputStream inputStream = entity.getContent();
            Object data = null;
            //判断是要返回字符串
            if (type.equals(RETURN_TYPE_STRING)) {
                reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("utf-8"))); 
                StringBuilder sb = new StringBuilder(1024);
                String item;
                while ((item = reader.readLine()) != null) {
                    sb.append(item + "\n");
                }
                String s = sb.toString();
                if (StringUtils.isNotEmpty(s)) {
                    data = s.substring(0, s.length() - 1);
                } 
            } else { //返回字节数组
                new IllegalStateException();
            } 
            Header[] headers = response.getAllHeaders();
            Map<String, Object> responseHeaders = new HashMap<String, Object>(); 
            for (int i = 0; i < headers.length; i++) {
                responseHeaders.put(headers[i].getName(), headers[i].getValue());
            }
            Map<String, Object> result = new HashMap<String, Object>(2);
            result.put("responseHeaders", responseHeaders);
            result.put("data", data); 
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    } 
}

2.示例 比如调用一个简单的顾客接口

(1)通过Test测试接口

     // 顾客接口
      @Test
      public void setPOInstock() { 
        //接口地址
        String url=""; 
        JSONArray cusArr = new JSONArray();
        JSONObject matObj1 = new JSONObject();
        matObj1.put("id", 99);
        matObj1.put("customerCode", "HK000008");
        matObj1.put("customerName", "公司");
        matObj1.put("customerType", "个体");
        matObj1.put("linkman", "天玄1");
        matObj1.put("telephone", "1518972584");
        cusArr.add(matObj1);
        Map<String, Object> map= HttpUtil.postJSONWithResponseHeaders(url ,JSONArray.toJSONString(cusArr), null);
        System.out.println(map);
    }

(2)通过postman调用接口

注:

  • postman调用类型,图片中为post方式。
  • 接口路径,图中为调用本地的路径
  • 接口传输的数据
  • 调用接口后的返回值。

如果想了解更多相关知识,可以到动力节点在线视频页面中免费观看教程视频进行学习。

0人推荐
共同学习,写下你的评论
0条评论
杨晶珍
程序员杨晶珍

98篇文章贡献357785字

相关课程 更多>

作者相关文章更多>

推荐相关文章更多>

Java面试题及答案整理

提枪策马乘胜追击04-21 20:01

Spring常见面试题

代码小兵92504-17 16:07

Java零基础实战项目——五子棋

代码小兵98804-25 13:57

Java string类详解

杨晶珍05-11 14:54

6道经典算法面试题

杨晶珍05-12 16:39

发评论

举报

0/150

取消