Java发送http请求的方式

Java 有多种方式可以发送 http 请求,这些方法主要分为两类,第一类是通过 Java 原生类HttpURLConnection发送请求,该方式使用起来相对繁琐一些,但底层逻辑清晰,有利于开发人员了解底层逻辑;第二类是通过第三方 Apache 旗下的专门用来发送 http 请求的 HttpClient 类,该类是对原生的HttpURLConnection类的扩展,功能强大,使用简单。

一、基于HttpURLConnection的请求发送

基于jdk1.7 HttpURLConnection 编写的发送http请求的函数,代码测试可用。顺便介绍了请求头部相关参数的细节,对于读者理解http协议具有一定的帮助,代码如下:

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * http请求工具类
 */
public class HttpUtil {

    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * http get 请求
     * @param url 链接
     * @return 请求返回内容
     */
    public static String doGet(String url) {

        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader reader = null;
        StringBuilder response = new StringBuilder();
        try {
            connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(15000);
            /// 设置请求头部
            connection.setRequestProperty("appKey", "123456");
            /// The "Accept: */*" header is added to tell the server that the client can understand and process all forms of response content types.
            /// 对于SringBoot架构后端使用@RestController注解的类,会返回json格式的数据, 相当于connection.setRequestProperty("Accept", "application/json");
            /// 当客户端未设置Accept头部时,默认值为"text/html;",此时服务端返回内容为html格式;
            connection.setRequestProperty("Accept", "*/*");
            /// 发起连接请求
            connection.connect();
            /// 读取返回数据
            inputStream = connection.getResponseCode() == 200 ? connection.getInputStream() : connection.getErrorStream();
            if(inputStream != null) {
                reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if(inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if(connection != null){
                try {
                    connection.disconnect();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return response.toString();
    }

    /**
     * http post请求
     * @param url 链接
     * @param params 参数内容,json格式或"name=smy&age=18&..."表单格式
     * @return 请求返回内容
     */
    public static String doPost(String url, @Nullable String params) {

        /// 确定请求参数类型
        String ContentType = "application/json";
        try{
            JSONObject.parseObject(params);
        }catch (Exception e){
            ContentType = "application/x-www-form-urlencoded";
        }

        StringBuilder response = new StringBuilder();
        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        BufferedReader br = null;
        try {
            connection= (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(15000);
            /// 设置请求头部
            connection.setRequestProperty("appKey", "123456");
            /// 设置是否可读取
            connection.setDoOutput(true);
            /// 设置响应可读取
            connection.setDoInput(true);
            /// 设置返回数据格式
            connection.setRequestProperty("Accept", "*/*");
            /// 设置请求参数类型
            connection.setRequestProperty("Content-Type", ContentType);
            /// 设置请求参数内容,并发送请求
            if(params != null && !params.isEmpty()) {
                outputStream = connection.getOutputStream();
                outputStream.write(params.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
            }

            /// 读取服务端响应
            if(connection.getResponseCode() == 200){
                inputStream = connection.getInputStream();
            }else{
                inputStream = connection.getErrorStream();
            }
            if(inputStream != null){
                br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                String line;
                if((line = br.readLine()) != null){
                    response.append(line);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if(connection != null){
                try {
                    connection.disconnect();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return response.toString();
    }

	/*****************************************
	 * 				测试代码
	 ****************************************/
    public static void main(String[] strs){

//        String response = HttpUtil.doGet("http://localhost:8081/car/getById/2");
//        System.out.println("请求返回:\n" + response);

        String url = "http://localhost:8081/car/getByConds1";
//        String params = "brand=vw&type=oil";
        String params = "{\"brand\":\"vw\", \"type\":\"oil\"}";

        String str = HttpUtil.doPost(url, params);
        System.out.println(str.toString());

        JSONObject jsonObject = JSONObject.parseObject(str);


    }
}

二、基于HttpClient的请求发送

Apache HttpClient 官网:http://hc.apache.org/httpcomponents-client-5.1.x/

下述示例代码基于Apache httpClient4.5编写:

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.Map.Entry;
 
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
 
public class HttpUtil {
 
    public static String doGet(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        try {
            httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Authorization", "Bearer 88888888-4444-4444-4444-cccccccccccc");
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)
                    .setConnectionRequestTimeout(35000)
                    .setSocketTimeout(60000)
                    .build();
            httpGet.setConfig(requestConfig);
            httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse .getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != httpResponse ) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
 
 
    public static String doPost(String url, Map<String, Object> paramMap) {
    
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        /// 设置请求时限参数
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)
                .setConnectionRequestTimeout(35000)
                .setSocketTimeout(60000)
                .build();
        httpPost.setConfig(requestConfig);
        /// 设置请求头部数据
        httpGet.setHeader("Authorization", "Bearer 88888888-4444-4444-4444-cccccccccccc");
        /// 设置请求参数类型
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        /// 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
            Iterator<Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            /// 发送请求,获取响应
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值