龙空技术网

100个Java工具类之6:用4种方式发起HTTP请求

金属时代ok 99

前言:

当前你们对“nethttpspost请求”大概比较注意,大家都需要分析一些“nethttpspost请求”的相关内容。那么小编同时在网络上搜集了一些有关“nethttpspost请求””的相关内容,希望咱们能喜欢,各位老铁们快快来学习一下吧!

一、通过common封装好的HttpClient(本文重点)

//1.1HttpClient发起GET请求public static String doGet(String url) {        // 创建Httpclient对象        CloseableHttpClient httpclient = HttpClients.createDefault();        CloseableHttpResponse response = null;        try {            // 创建uri            URIBuilder builder = new URIBuilder(url);            URI uri = builder.build();            // 创建http GET请求            HttpGet httpGet = new HttpGet(uri);            httpGet.setHeader("Content-Type", "application/json;charset=utf-8");            // 执行请求            response = httpclient.execute(httpGet);            String result = "";            if (response.getStatusLine().getStatusCode() == 200) {                result = EntityUtils.toString(response.getEntity(), "UTF-8");            }        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (response != null) {                    response.close();                }                httpclient.close();            } catch (IOException e) {                e.printStackTrace();            }        }        return result;    }//1.2HttpClient发起POST请求public static String doPost(String url, Map<String, Object> param) {        //设置响应时间        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(30000).setSocketTimeout(30000)                .setConnectTimeout(30000).build();        // 创建Httpclient对象        CloseableHttpClient httpclient = HttpClients.createDefault();        CloseableHttpResponse response = null;        try {            // 创建http POST请求            HttpPost httpPost = new HttpPost(url);            httpPost.setConfig(requestConfig);            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");            if (headerMap != null) {                for (String key : headerMap.keySet()) {                    httpPost.setHeader(key, headerMap.get(key));                }            }            // 设置参数            StringEntity entity = new StringEntity(JSON.toJSONString(param), "UTF-8");            httpPost.setEntity(entity);            // 执行请求            response = httpclient.execute(httpPost);            String result = "";            if (response.getStatusLine().getStatusCode() == 200) {                result = EntityUtils.toString(response.getEntity(), "UTF-8");            }        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (response != null) {                    response.close();                }                httpclient.close();            } catch (IOException e) {                e.printStackTrace();            }        }        return result;    }
二、通过SpringBoot-RestTemplate(本文重点)

Spring RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,

RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率

由于代码简洁,效率高,因此只要是做SpringBoot项目,都会使用这种方式。

//2.1 RestTemplate发送GET请求 get请求是通过url传递参数 @Autowired private RestTemplate restTemplate;String url = ";;ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);String body = forEntity.getBody();//2.2 RestTemplate发送POST请求Map<String, Object> map = new HashMap<>();map.put("name", "张三");String url = ";;ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,stu,String.class);return responseEntity.getBody();
三、通过JDK网络类Java.net.HttpURLConnection
import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;public class ConnectUtil {    /**     * HttpURLConnection的post请求方式     *     * @param url     请求地址     * @param params  请求参数 json格式     * @param charset 编码     * @return     * @throws Exception     */    public static JSONObject doPostJson(String url, String params, String charset) {        JSONObject jsonObject = new JSONObject();        try {            // 建立连接             URL realURL = new URL(url);            HttpURLConnection conn = (HttpURLConnection) realURL.openConnection();            //设置连接属性            // 设定请求的方法为"POST",默认是GET             conn.setRequestMethod("POST");            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true, 默认情况下是false;             conn.setDoOutput(true);            // 设置是否从httpUrlConnection读入,默认情况下是true;             conn.setDoInput(true);            // Post 请求不能使用缓存             conn.setUseCaches(false);            // 设置请求属性            conn.setRequestProperty("Connection", "Keep-Alive");            conn.setRequestProperty("Charset", charset);            // 设定传送的内容类型是json,utf-8字符编码            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");            // 设置接收类型            conn.setRequestProperty("accept", "application/json");            // 往服务器里面发送数据            if (params != null && params.length() > 0) {                byte[] writebytes = params.getBytes();                // 设置文件长度                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));                // 建立输出流,并写入数据                OutputStream outwritestream = conn.getOutputStream();                outwritestream.write(params.getBytes());                outwritestream.flush();                outwritestream.close();            }            // 获得响应状态            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));            String line;            String resultString = "";            while ((line = reader.readLine()) != null) {                resultString += line;            }            jsonObject = JSON.parseObject(resultString);        } catch (Exception e) {            e.printStackTrace();        }        return jsonObject;    }}
四、通过Apache封装的CloseableHttpClient

CloseableHttpClient是在HttpClient的扩展的,是目前推荐的用法。不仅可以简单设置请求头,还可以利用fastjson转换请求或返回结果字符串为json格式。

//4.1 CloseableHttpClient发送get请求    private String doGet() {        CloseableHttpClient httpClient = HttpClients.createDefault();        CloseableHttpResponse response = null;        String result = null;        try {            URIBuilder uri = new URIBuilder("请求路径");            List<NameValuePair> list = new LinkedList<>();            BasicNameValuePair param1 = new BasicNameValuePair("key1", "value1");            BasicNameValuePair param2 = new BasicNameValuePair("key2", "value2");            list.add(param1);            list.add(param2);            uri.setParameters(list);            HttpGet httpGet = new HttpGet(uri.build());                 //设置请求状态参数            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(3000)                      .setSocketTimeout(3000).setConnectTimeout(3000).build();            httpGet.setConfig(requestConfig);            response = httpClient.execute(httpGet);            int status = response.getStatusLine().getStatusCode();            if (status == HttpStatus.SC_OK) {//请求成功                HttpEntity httpEntity = response.getEntity();                if (httpEntity != null) {                    result = EntityUtils.toString(httpEntity, "UTF-8");                    EntityUtils.consume(httpEntity);//关闭资源                      JSONObject jsonResult = JSONObject.fromObject(result);                      JSONArray jsonArray = jsonResult.getJSONArray("data");                      for (int i = 0; i < jsonArray.size(); i++) {                        result = jsonArray.getJSONObject(i).getString("对应key")                      }                    return result;                }            }        } catch (Exception e) {            e.printStackTrace();        } finally {            if (response != null) {                try {                    response.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (httpClient != null) {                try {                    httpClient.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return result;    }//4.2 CloseableHttpClient发送post请求    private void doPost() {        HttpPost httpPost = new HttpPost("请求路径");        CloseableHttpClient client = HttpClients.createDefault();        List params = new ArrayList();        params.add(new BasicNameValuePair("key1", "value1"));        params.add(new BasicNameValuePair("key2", "value2"));        try {            HttpEntity httpEntity = new UrlEncodedFormEntity(params, "UTF-8");            httpPost.setEntity(httpEntity);            response = client.execute(httpPost);        } catch (Exception e) {            e.printStackTrace();        } finally {            if (response != null) {                try {                    response.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (client != null) {                try {                    client.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }

发起Http请求共有8中请求方式,分别是Get、Post、Put、Delete、opions、Head、Trace、Connect。

HTTP POST和GET的区别

1、传送方式不同:GET在HTTP头部传送参数,Post在HTTP 请求内容里传送数据

2、URL内容显示不同:GET方法传输数据时参数会在URL中显示,而POST不会显示

3、传输内容大小不同:GET方法由于受到URL长度的限制,只能传递大约1024字节;POST传输的数据量大,可达到2M

4、请求目的不同:GET用来从服务器取数据;POST 用来向上放数据,GET也能够向服务器传送较少的数据,目的只是描述所取的数据

标签: #nethttpspost请求