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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章