Java 调用 web 接口的方式 HttpUrlConnection

直接上代码

唠叨两句:建议使用 httpclient 库调用 web 接口,因为 HttpUrlConnection 写起来非常容易出错

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * Http方式调用接口
 * 
 * @author karl
 * @// TODO: 2020/4/26
 */
public class HttpUrlConnectionUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpUrlConnectionUtils.class);

    /**
     * post方式调用接口
     *
     * @param url 接口地址
     * @param params 参数列表
     * @return 
     */
    public static String doPost(String url, String params) {
        OutputStream out = null;
        DataOutputStream dataOutputStream = null;
        InputStream in = null;
        ByteArrayOutputStream baos = null;
        try {
            URLConnection urlConnection = new URL(url).openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
            // 设置是否向httpUrlConnection输出,post请求,参数要放在http正文内,因此需要设为true,
            // 默认情况下是false;
            httpUrlConnection.setDoOutput(true);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            httpUrlConnection.setDoInput(true);
            // 忽略缓存
            httpUrlConnection.setUseCaches(false);
            // 设定请求的方法为"POST",默认是GET
            httpUrlConnection.setRequestMethod("POST");
            // 设置http头
            httpUrlConnection.setRequestProperty("Content-type","application/json");
            httpUrlConnection.setRequestProperty("Charset", "UTF-8");
            httpUrlConnection.connect();

            out = httpUrlConnection.getOutputStream();
            dataOutputStream = new DataOutputStream(out);
            dataOutputStream.write(params.getBytes("UTF-8"));
            dataOutputStream.flush();
            out.flush();

            // 获得响应状态
            int responseCode = httpUrlConnection.getResponseCode();
            if (HttpURLConnection.HTTP_OK != responseCode) {
                return null;
            }

            // 成功响应
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            in = httpUrlConnection.getInputStream();
            while ((len = in.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
                baos.flush();
            }
            return baos.toString("UTF-8");
        } catch (Exception e) {
            logger.error("HttpUrlConnection doPost: failed", e);
            return null;
        } finally {
            closeConnection(baos, in, dataOutputStream, out);
        }
    }

    public static void closeConnection(ByteArrayOutputStream baos, InputStream in, DataOutputStream dos, OutputStream out){
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException e) {
                logger.error("HttpUrlConnection closeConnection: failed", e);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error("HttpUrlConnection closeConnection: failed", e);
            }
        }
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                logger.error("HttpUrlConnection closeConnection: failed", e);
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.error("HttpUrlConnection closeConnection: failed", e);
            }
        }
    }

    /**
     * 组建请求参数
     *
     * @param params parameters map
     */
    public static String getRequestBody(Map<String, String> params){
        Gson gson = new Gson();
        return gson.toJson(params);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值