java 发送 http 请求

概述

在java中,我们发送http请求(get、post) 主要有两种方法

  • 使用Java原生HttpURLConnection
  • 使用第三方库,例如 Apache的HttpClient库

HttpURLConnection

下面的代码分别是使用 get 进行 http 访问和 使用 post 进行 https 访问的例子

package com.mkyong;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpURLConnectionExample {

    private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String[] args) throws Exception {

        HttpURLConnectionExample http = new HttpURLConnectionExample();

        System.out.println("Testing 1 - Send Http GET request");
        http.sendGet();

        System.out.println("\nTesting 2 - Send Http POST request");
        http.sendPost();

    }

    // HTTP GET请求
    private void sendGet() throws Exception {

        String url = "http://www.google.com/search?q=mkyong";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //默认值我GET
        con.setRequestMethod("GET");

        //添加请求头
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //打印结果
        System.out.println(response.toString());

    }

    // HTTP POST请求
    private void sendPost() throws Exception {

        String url = "https://selfsolve.apple.com/wcResults.do";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //添加请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

        //发送Post请求
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //打印结果
        System.out.println(response.toString());

    }

}

输出结果

Sending 'GET' request to URL : http://www.google.com/search?q=mkyong
Response Code : 200
Google search result...

Testing 2 - Send Http POST request

Sending 'POST' request to URL : https://selfsolve.apple.com/wcResults.do
Post parameters : sn=C02G8416DRJM&cn=&locale=&caller=&num=12345
Response Code : 200
Apple product detail...

HttpClient 第三方库

下面是两个分别封装进行纯参数 post 请求和 带文件的 post 请求例子

    public String httpPost(String url, List<NameValuePair> nvpList, int requestTimeout, int connectTimeout, int socketTimeout) {
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(requestTimeout)
                .setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();       //设置各种超时时间
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(config).build();       //build httpClient
        HttpPost httpPost = new HttpPost(url);         //新建post请求操作类
        CloseableHttpResponse response;               //返回
        String body;

        try {
            if (nvpList != null || !nvpList.isEmpty()) {
                httpPost.setEntity(new UrlEncodedFormEntity(nvpList, "utf-8"));          //设置post的参数
            }

            response = httpclient.execute(httpPost);                   //执行 post
            HttpEntity entity = response.getEntity();
            body = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return body;
    }

    public String httpPost(String url, List<NameValuePair> nvpList, final Map<String, File> files, int requestTimeout, int connectTimeout, int socketTimeout) {
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(requestTimeout)
                .setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build(); 
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(config).build();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response;
        String body;

        try {
            httpPost.setEntity(makeMultipartEntity(nvpList, files));             //根据post参数和文件生成post请求的具体信息

            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            body = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }

    private static HttpEntity makeMultipartEntity(List<NameValuePair> params, final Map<String, File> files) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();           //旧版 HttpClient 使用 MultipartEntity, 已经废弃
        builder.setMode(HttpMultipartMode.STRICT);                 //设置模式,STRICT 为默认模式(RFC 822, RFC 2045, RFC 2046 compliant), BROWSER_COMPATIBLE 为浏览器兼容模式(browser-compatible mode, i.e.), RFC6532(RFC 6532 compliant),一般选 STRICT 或者 BROWSER_COMPATIBLE
        if (params != null && params.size() > 0) {
            for (NameValuePair p : params) {
                builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8"));    //生成参数信息
            }
        }
        if (files != null && files.size() > 0) {
            Set<Map.Entry<String, File>> entries = files.entrySet();
            for (Map.Entry<String, File> entry : entries) {
                builder.addBinaryBody("file", entry.getValue());        //生成文件信息,另外一种方法为使用 addPart, 那种不能随意设置 ContentType,具体可以参考后面的一个链接网站
            }
        }
        return builder.build();
    }

参考链接

如何在Java中发送HTTP GET/POST请求
HttpClient使用MultipartEntityBuilder实现多文件上传

posted @ 2018-03-28 11:01  玩出新意  阅读(1230)  评论(0编辑  收藏  举报