Http请求工具类

时间:2021-08-12
本文章向大家介绍Http请求工具类,主要包括Http请求工具类使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Http请求工具类 HttpUtil.java

package com.example.demo.util;

import com.google.gson.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Set;

public class HttpUtil {

    public static String post(String httpUrl, Object param) throws IOException {
        String paramStr = toUrlString(param);
        return post(httpUrl, param);
    }

    private static String post(String httpUrl, String param) throws IOException {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(10000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            String ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            connection.setRequestProperty("Content-Type", ContentType);
            os = connection.getOutputStream();
            os.write(param.getBytes());
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                StringBuilder sbf = new StringBuilder();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }

    public static String toUrlString(Object object) throws UnsupportedEncodingException {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        String json = gson.toJson(object);
        JsonElement jsonElement = JsonParser.parseString(json);
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        Set<String> keys = jsonObject.keySet();
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            String encode = URLEncoder.encode(jsonObject.get(key).getAsString(), "UTF-8");
            sb.append(key).append("=").append(encode).append("&");
        }
        return sb.toString();
    }

}

===========END===========

作者:一柒微笑
欢迎转载,但未经作者同意须在文章页面给出原文连接,否则保留追究法律责任的权利

原文地址:https://www.cnblogs.com/zhouxuezheng/p/15134393.html