基础工具类---HTTP协议

本文介绍了一个包含多种HTTP请求方法的工具类实现,如GET、POST、PUT等,并使用了Java标准库及Spring框架来简化HTTP交互过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.ftvalue.customer.util;

/**

 *HttpUtil.java
 */

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


/**
 * @author danhui
 * @version 1.0
 * @filename HttpUtil.java
 */
@Slf4j
public class HttpUtil {


    /*public static String GET(String url){
        HttpClient client =new DefaultHttpClient();
        HttpGet GET= new HttpGet(url);
        UrlEncodedFormEntity entity =null;
        String aa ="";
        try {
            HttpResponse ss = client.execute(GET);
            aa = EntityUtils.toString(ss.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return aa;
    }*/

    public static String http(String url, Map<String, String> params) throws IOException {
        URL u = null;
        HttpURLConnection con = null;
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Entry<String, String> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        System.out.println("send_url:" + url );
        u = new URL(url);
        con = (HttpURLConnection) u.openConnection();
        con.setRequestMethod("POST");
        con.setConnectTimeout(400000);
        con.setReadTimeout(400000);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setRequestProperty("Content-Type","application/json");
        con.connect();

        StringBuffer buffer = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        String temp;
        while ((temp = br.readLine()) != null) {
            buffer.append(temp);
            buffer.append("\n");
        }
        con.disconnect();
        return buffer.toString();

    }


    public static String sendPost(String url, Map<String, String> params) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Entry<String, String> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
        }

        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
            //out = new PrintWriter(conn.getOutputStream());
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
            //System.out.println(""+sb.toString());
            out.print(sb.toString());
            //out.print(params);

            out.flush();
            //in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String httpPut(String url, Map<String, String> params) throws Exception {
        URL u = null;

        HttpURLConnection con = null;

        // 构建请求参数

        StringBuffer sb = new StringBuffer();
        String sendString = "" ;
        if (params != null) {

            for (Entry<String, String> e : params.entrySet()) {

                sb.append(e.getKey());

                sb.append("=");

                sb.append(e.getValue());

                sb.append("&");

            }

            sendString = sb.substring(0, sb.length() - 1);

        }

        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("PUT");
            con.setConnectTimeout(6000);
            con.setReadTimeout(1800000);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con
                .getOutputStream(), "UTF-8");
            osw.write(sendString);
            osw.flush();
            osw.close();
        } catch (Exception e) {
            throw new Exception("与服务器连接发生错误");
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                .getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
        } catch (Exception e) {
            throw new Exception("从服务器获取数据失败");
        }
        return buffer.toString();
    }

    public static String httpGet(String url, Map<String, String> params) throws Exception {
        URL u = null;

        HttpURLConnection con = null;

        // 构建请求参数

        StringBuffer sb = new StringBuffer();
        String sendString = "" ;
        if (params != null) {

            for (Entry<String, String> e : params.entrySet()) {

                sb.append(e.getKey());

                sb.append("=");

                sb.append(e.getValue());

                sb.append("&");

            }

            sendString = sb.substring(0, sb.length() - 1);

        }

        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(50000);
            con.setReadTimeout(1800000);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con
                    .getOutputStream(), "UTF-8");
            osw.write(sendString);
            osw.flush();
            osw.close();
        } catch (Exception e) {
            throw new Exception("与服务器连接发生错误");
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                    .getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
        } catch (Exception e) {
            throw new Exception("从服务器获取数据失败");
        }
        return buffer.toString();
    }

    public static String httpPost(String url, Map<String, Object> params) throws Exception {
        URL u = null;

        HttpURLConnection con = null;

        // 构建请求参数

        StringBuffer sb = new StringBuffer();
        String sendString = "" ;
        if (params != null) {

            for (Entry<String, Object> e : params.entrySet()) {

                sb.append(e.getKey());

                sb.append("=");

                sb.append(e.getValue());

                sb.append("&");

            }

            sendString = sb.substring(0, sb.length() - 1);

        }

        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setConnectTimeout(50000);
            con.setReadTimeout(1800000);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con
                    .getOutputStream(), "UTF-8");
            osw.write(sendString);
            osw.flush();
            osw.close();
        } catch (Exception e) {
            throw new Exception("与服务器连接发生错误");
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                    .getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
        } catch (Exception e) {
            throw new Exception("从服务器获取数据失败");
        }
        return buffer.toString();
    }

    public static String getResponseBodyPut(Map<String, String> params, String serverUrl) {
        RestTemplate restTemplate = new RestTemplate();
        FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
        List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>();
        partConverters.add(new ByteArrayHttpMessageConverter());
        UTF8StringHttpMessageConverter utf8StringHttpMessageConverter = new UTF8StringHttpMessageConverter();
        utf8StringHttpMessageConverter.setWriteAcceptCharset(false);
        partConverters.add(utf8StringHttpMessageConverter);
        partConverters.add(new ResourceHttpMessageConverter());
        formHttpMessageConverter.setPartConverters(partConverters);
        formHttpMessageConverter.setCharset(Charset.forName("UTF-8"));
        restTemplate.getMessageConverters().add(0, formHttpMessageConverter);
        restTemplate.getMessageConverters().add(0, new UTF8StringHttpMessageConverter());

        String responseBody = "";
        MultiValueMap headers = new LinkedMultiValueMap();
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED.toString());
        HttpEntity requestEntity = new HttpEntity(toMultiValueMap(params), headers);
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(URI.create(serverUrl),
                    HttpMethod.PUT, requestEntity, String.class);
            responseBody = responseEntity.getBody();
        } catch (HttpStatusCodeException e) {
            responseBody = e.getResponseBodyAsString();
        } catch (Exception e) {
            if (e.getMessage().contains("Connection refused")) {
            } else {
            }
        }
        return responseBody;
    }




    public static String getResponseBody(Map<String, String> params, String serverUrl) {
        RestTemplate restTemplate = new RestTemplate();
        FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
        List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>();
        partConverters.add(new ByteArrayHttpMessageConverter());
        UTF8StringHttpMessageConverter utf8StringHttpMessageConverter = new UTF8StringHttpMessageConverter();
        utf8StringHttpMessageConverter.setWriteAcceptCharset(false);
        partConverters.add(utf8StringHttpMessageConverter);
        partConverters.add(new ResourceHttpMessageConverter());
        formHttpMessageConverter.setPartConverters(partConverters);
        formHttpMessageConverter.setCharset(Charset.forName("UTF-8"));
        restTemplate.getMessageConverters().add(0, formHttpMessageConverter);
        restTemplate.getMessageConverters().add(0, new UTF8StringHttpMessageConverter());

        String responseBody = "";
        MultiValueMap headers = new LinkedMultiValueMap();
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED.toString());
        HttpEntity requestEntity = new HttpEntity(toMultiValueMap(params), headers);
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(URI.create(serverUrl),
                HttpMethod.POST, requestEntity, String.class);
            responseBody = responseEntity.getBody();
        } catch (HttpStatusCodeException e) {
            responseBody = e.getResponseBodyAsString();
        } catch (Exception e) {
            if (e.getMessage().contains("Connection refused")) {
            } else {
            }
        }
        return responseBody;
    }

    public static String getResponseBodyGet(Map<String, String> params, String serverUrl) {
        RestTemplate restTemplate = new RestTemplate();
        FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
        List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>();
        partConverters.add(new ByteArrayHttpMessageConverter());
        UTF8StringHttpMessageConverter utf8StringHttpMessageConverter = new UTF8StringHttpMessageConverter();
        utf8StringHttpMessageConverter.setWriteAcceptCharset(false);
        partConverters.add(utf8StringHttpMessageConverter);
        partConverters.add(new ResourceHttpMessageConverter());
        formHttpMessageConverter.setPartConverters(partConverters);
        formHttpMessageConverter.setCharset(Charset.forName("UTF-8"));
        restTemplate.getMessageConverters().add(0, formHttpMessageConverter);
        restTemplate.getMessageConverters().add(0, new UTF8StringHttpMessageConverter());

        String responseBody = "";
        MultiValueMap headers = new LinkedMultiValueMap();
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED.toString());
        HttpEntity requestEntity = new HttpEntity(toMultiValueMap(params), headers);
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(URI.create(serverUrl),
                    HttpMethod.GET, requestEntity, String.class);
            responseBody = responseEntity.getBody();
        } catch (HttpStatusCodeException e) {
            responseBody = e.getResponseBodyAsString();
        } catch (Exception e) {
            if (e.getMessage().contains("Connection refused")) {
            } else {
            }
        }
        return responseBody;
    }



    static MultiValueMap toMultiValueMap(Map<String, String> map) {
        MultiValueMap multiValueMap = new LinkedMultiValueMap();
        for (String key : map.keySet()) {
            multiValueMap.add(key, map.get(key));
        }
        return multiValueMap;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

化猿和尚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值