Java发送http请求

  Java发送http请求网上很多资料,这里只是记录一下我的一个工具类。直接代码了。

package com.JohanChan;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtils {
    /**
     * 向指定服务器发送GET请求
     * */
    private static int defTimeOut = 2500;
    public static String sendGet(String url,Integer timeOut) {
        BufferedReader in = null;
        try {
            if (timeOut == null || timeOut <= 0)
                timeOut = defTimeOut;
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setConnectTimeout(timeOut);
            connection.setReadTimeout(timeOut);
            // 建立实际的连接
            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }

    //post请求方法
    public static String sendPost(String url, String data) {
        String response = null;

        try {
            CloseableHttpClient httpclient = null;
            CloseableHttpResponse httpresponse = null;
            try {
                httpclient = HttpClients.createDefault();
                HttpPost httppost = new HttpPost(url);
                // 构造消息头
//                httppost.setHeader("Host","192.168.0.231:18080");
                httppost.setHeader("Content-type", "application/json; charset=utf-8");
//                httppost.setHeader("Connection", " keep-alive");
                /*if (StringUtils.isNotEmpty(auth)){
                    httppost.setHeader("Authorization",auth);
                    httppost.setHeader("Origin","http://192.168.0.231:18080");
                }*/

                StringEntity stringentity = new StringEntity(data, ContentType.create("text/json", "UTF-8"));
                stringentity.setContentType("application/json");
                httppost.setEntity(stringentity);
                httpresponse = httpclient.execute(httppost);
                response = EntityUtils.toString(httpresponse.getEntity(), "UTF-8");
            } finally {
                if (httpclient != null) {
                    httpclient.close();
                }
                if (httpresponse != null) {
                    httpresponse.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }


}

 

posted @ 2021-03-03 10:57  胜金  阅读(1111)  评论(0编辑  收藏  举报