java程序如何实现调取外部接口

其实不就是java访问网址嘛。 “接口”,抽象概念矣

https://blog.csdn.net/dunegao/article/details/79032950
https://bbs.csdn.net/topics/392160570
http://www.cnblogs.com/dougest/p/6580960.html

记个工具类吧:

package com.cowain.base.common.utils.okhttp;

import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;


public class OkHttpClients {
    public static <T> OkhttpResult<T> get(OkHttpParam restParam, Class<T> tClass) throws Exception {
        String url = restParam.getApiUrl();
        if (restParam.getApiPath() != null) {
            url = url + restParam.getApiPath();
        }
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        return exec(restParam, request, tClass);
    }
    /**
     * POST请求json数据
     */
    public static <T> OkhttpResult<T> post(OkHttpParam restParam, String reqJsonData, Class<T> tClass) throws Exception {
        String url = restParam.getApiUrl();
        if (restParam.getApiPath() != null) {
            url = url + restParam.getApiPath();
        }
        RequestBody body = RequestBody.create(restParam.getMediaType(), reqJsonData);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return exec(restParam, request, tClass);

    }


    /**
     * POST请求map数据
     */
    public static <T> OkhttpResult<T> post(OkHttpParam restParam, Map<String, String> parms, Class<T> tClass) throws Exception {
        String url = restParam.getApiUrl();
        if (restParam.getApiPath() != null) {
            url = url + restParam.getApiPath();
        }
        FormBody.Builder builder = new FormBody.Builder();
        if (parms != null) {
            for (Map.Entry<String, String> entry : parms.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        FormBody body = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return exec(restParam, request, tClass);
    }

    /**
     * 返回值封装成对象
     */
    private static <T> OkhttpResult<T> exec(
            OkHttpParam restParam,
            Request request,
            Class<T> tClass) throws Exception {
        OkhttpResult clientResult = exec(restParam, request);
        String result = clientResult.getResult();
        int status = clientResult.getStatus();
        T t = null;
        if (status == 200) {
            if (result != null && "".equalsIgnoreCase(result)) {
                t = JSON.parseObject(result, tClass);
            }
        } else {
            try {
                result = JSON.parseObject(result, String.class);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return new OkhttpResult<>(clientResult.getStatus(), result, t);
    }

    /**
     * 执行方法
     */
    private static OkhttpResult exec(
            OkHttpParam restParam,
            Request request) throws Exception {
        OkhttpResult result = null;
        okhttp3.OkHttpClient client = null;
        ResponseBody responseBody = null;
        try {
            client = new okhttp3.OkHttpClient();
            client.newBuilder()
                    .connectTimeout(restParam.getConnectTimeout(), TimeUnit.MILLISECONDS)
                    .readTimeout(restParam.getReadTimeout(), TimeUnit.MILLISECONDS)
                    .writeTimeout(restParam.getWriteTimeout(), TimeUnit.MILLISECONDS);
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                responseBody = response.body();
                if (responseBody != null) {
                    String responseString = responseBody.string();
                    result = new OkhttpResult<>(response.code(), responseString, null);
                }
            } else {
                throw new Exception(response.message());
            }
        } catch (Exception ex) {
            throw new Exception(ex.getMessage());
        } finally {
            if (responseBody != null) {
                responseBody.close();
            }
            if (client != null) {
                client.dispatcher().executorService().shutdown();   //清除并关闭线程池
                client.connectionPool().evictAll();                 //清除并关闭连接池
                try {
                    if (client.cache() != null) {
                        client.cache().close();                         //清除cache
                    }
                } catch (IOException e) {
                    throw new Exception(e.getMessage());
                }
            }
        }
        return result;
    }
}
package com.cowain.base.common.utils.okhttp ;


import okhttp3.MediaType;

public class OkHttpParam {

    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 接口URL
     */
    private String apiUrl;
    /**
     * 接口路径
     */
    private String apiPath;
    /**
     * 读取超时时间
     */
    private int readTimeout = 30 * 1000;
    /**
     * 写入超时时间
     */
    private int writeTimeout = 30 * 1000;
    /**
     * 连接超时时间
     */
    private int connectTimeout = 2 * 1000;
    /**
     * 编码类型
     */
    private MediaType mediaType = MEDIA_TYPE_JSON;



    public String getApiUrl() {

        return apiUrl;

    }



    public void setApiUrl(String apiUrl) {

        this.apiUrl = apiUrl;

    }



    public String getApiPath() {

        return apiPath;

    }



    public void setApiPath(String apiPath) {

        this.apiPath = apiPath;

    }



    public int getReadTimeout() {

        return readTimeout;

    }



    public void setReadTimeout(int readTimeout) {

        this.readTimeout = readTimeout;

    }



    public int getWriteTimeout() {

        return writeTimeout;

    }



    public void setWriteTimeout(int writeTimeout) {

        this.writeTimeout = writeTimeout;

    }



    public int getConnectTimeout() {

        return connectTimeout;

    }



    public void setConnectTimeout(int connectTimeout) {

        this.connectTimeout = connectTimeout;

    }



    public MediaType getMediaType() {

        return mediaType;

    }



    public void setMediaType(MediaType mediaType) {

        this.mediaType = mediaType;

    }

}

package com.cowain.base.common.utils.okhttp;


public class OkhttpResult<T> {
    private int status;
    private String result;
    private T resultObject;
    public OkhttpResult() {
    }
    public OkhttpResult(int status, String result, T resultObject) {
        this.status = status;
        this.result = result;
        this.resultObject = resultObject;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    public T getResultObject() {
        return resultObject;
    }
    public void setResultObject(T resultObject) {
        this.resultObject = resultObject;
    }
}

调用:

 /**
     * 发射场景权限数据
     * @param jsonObject
     */
    private void sendPermission(JSONObject jsonObject) {
        OkHttpParam param = new OkHttpParam();
   
        param.setApiUrl(OutApiUrls.IBMS_SCENE_URL);
        OkhttpResult<String> result = null;
        try {
            long startTime = System.currentTimeMillis();
            log.info("开始时间 = " + startTime);
            log.info("发射数据 = " + jsonObject.toJSONString());
            // 返回数据类型 OkhttpResult<String>
            //发射(post)
            result = OkHttpClients.post(param, jsonObject.toJSONString(), String.class);
            long endTime = System.currentTimeMillis();
            log.info("结束时间 = " + endTime);
         
            log.info("【成功】,返回值 = " + JSON.toJSONString(result) + "]");
        } catch (Exception e) {
            long endErrorTime = System.currentTimeMillis();
            log.info("结束时间 = " + endErrorTime);
         
            log.info("【错误】,这批数据   = " + JSON.toJSONString(jsonObject) + "]");
            e.printStackTrace();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值