Java学习笔记 31 - 使用HTTP协议发送GET/POST请求(详细)

使用HTTP协议发送GET/POST请求,可以有多种方式,以下详细介绍两种方法。
一、JDK 的 java.net 包中提供的访问 HTTP 协议功能发送GET/POST请求
1、发送get请求详细步骤
1)创建要请求的URL实例

            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);

2)打开和实例URL的连接

            URLConnection connection = realUrl.openConnection();

3)为已打开的连接设置HTTP请求通用的属性,如accept,connection,user-agent.

            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

4)在设置好属性的连接基础上,执行实际的连接,即发送请求

            connection.connect();

5)获取get请求的响应头

            Map> map = connection.getHeaderFields();
             // 遍历所有的响应头字段
             for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
              }

6)获取get请求的响应结果.这里可以通过BufferedReader输入流来读取URL的响应

             BufferedReader in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
             String line;
             while ((line = in.readLine()) != null) {
                result += line;
              }

也可以使用工具类IOUtils的toString方法获取响应结果.

              result = IOUtils.toString(connection.getInputStream(),"utf-8");

7)关闭流,关闭连接

   // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

2、发送post请求详细步骤
1)创建要请求的URL实例

            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);

2)打开和实例URL的连接

            URLConnection connection = realUrl.openConnection();

3)为已打开的连接设置HTTP请求通用的属性,如accept,connection,user-agent.

            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

4)由于post请求,参数是放在body中,需要设置连接中允许写入参数

        conn.setDoOutput(true);
            conn.setDoInput(true);

5)获取URLConnection对象对应的输出流

         PrintWriter out = new PrintWriter(conn.getOutputStream());

6)写入发送post请求需要的参数

         out.print(param);
             out.flush();

6)获取get请求的响应结果.这里可以通过BufferedReader输入流来读取URL的响应

             BufferedReader in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
             String line;
             while ((line = in.readLine()) != null) {
                result += line;
              }
    也可以使用工具类IOUtils的toString方法获取响应结果.
           List list = IOUtils.readLines(conn.getInputStream(),"UTF-8");
            for(String s:list){
                System.out.println(s);
            }
7)关闭流,关闭连接

完整代码:

package com.sc.http;

import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpRequest {
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和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.connect();
            // 获取所有响应头字段
            Map> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
             //定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

            result = IOUtils.toString(connection.getInputStream(),"utf-8");
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(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)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
//            List list = IOUtils.readLines(conn.getInputStream(),"UTF-8");
//            for(String s:list){
//                System.out.println(s);
//            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        //发送 GET 请求
//        String s=HttpRequest.sendGet("http://www.baidu.com", "key=123&v=456");
//        System.out.println(s);

        //发送 POST 请求
        String sr=HttpRequest.sendPost("http://192.168.200.66/zabbix/screens.php", "ddreset=1");
        System.out.println(sr);
    }
}

二、使用org.apache.http包下的HttpClient发送GET/POST请求
HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性。它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。
1、HttpClient发送get请求(无参数)详细步骤
1). 创建HttpClient对象

            CloseableHttpClient httpclient = HttpClients.createDefault();

2). 创建请求方法的实例,并指定请求URL

            HttpGet get = new HttpGet("http://www.baidu.com");  

3). 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

            CloseableHttpResponse response= httpclient.execute(get);

4).获取get请求的响应结果.调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容

            HttpEntity entity = response.getEntity();

获取响应状态

 int code = response.getStatusLine().getStatusCode();
 System.out.println(" code "+code);

5).通过BufferedReader输入流读取响应结果

            BufferedReader  in = new BufferedReader(
                    new InputStreamReader(entity.getContent(),"UTF-8"));
            String line;
            String result="";
            while ((line = in.readLine()) != null) {
                result += line+"\n";
            }
            System.out.println(result);
  可以使用工具类IOUtils的toString方法获取响应结果.
           List list = IOUtils.readLines(entity.getContent(),"UTF-8");
            for(String s:list){
                System.out.println(s);
            }
   或者:
      result=IOUtils.toString(entity.getContent(),"utf-8");
   可以使用EntityUtils的toString方法获取响应结果.(推荐使用)
           if(entity!=null){
                System.out.println(EntityUtils.toString(entity));
            }

6).释放连接,无论执行方法是否成功,都必须释放连接
完整代码:

package com.sc.http;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientTest2 {

    public static void main(String[] args)  {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        CloseableHttpResponse response = null;
        HttpEntity  entity=null;
        try {
            HttpGet get = new HttpGet("http://www.baidu.com");
            response = httpclient.execute(get);
            entity = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            System.out.println(" code "+code);
            if(entity!=null){
                System.out.println(EntityUtils.toString(entity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                EntityUtils.consume(entity);
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2、HttpClient发送post请求详细步骤
1). 创建HttpClient对象

            CloseableHttpClient httpclient = HttpClients.createDefault();

2). 创建请求方法的实例,并指定请求URL

            HttpPost post = new HttpPost("http://123.58.251.183:8080/goods/UserServlet");

3). 创建HttpEntity,模拟一个表单,用于包装参数
POST请求,参数是放在body内,所以需要构建UrlEncodedFormEntity
而UrlEncodedFormEntity需要传入的参数类型为List且List中装入的是NameValuePair类型的集合
NameValuePair是一个接口,它的实现类是BasicNameValuePair
BasicNameValuePair类的构造方法中需要传入两个参数key,value

            List list = new ArrayList();
            list.add(new BasicNameValuePair("method","loginMobile"));
            list.add(new BasicNameValuePair("loginname","abc"));
            list.add(new BasicNameValuePair("loginpass","abc"));
            HttpEntity postEntity = new UrlEncodedFormEntity(list);
            post.setEntity(postEntity);

4). 若需要使用例如Fidder工具抓包,就需要设置代理.(无需抓包时,可省略此步)

            HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
            RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
            post.setConfig(config);

5). 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

            CloseableHttpResponse response= httpclient.execute(get);

6).获取get请求的响应结果.调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容

            HttpEntity entity = response.getEntity();

获取响应状态

 int code = response.getStatusLine().getStatusCode();
 System.out.println(" code "+code);

7).通过BufferedReader输入流读取响应结果

            BufferedReader  in = new BufferedReader(
                    new InputStreamReader(entity.getContent(),"UTF-8"));
            String line;
            String result="";
            while ((line = in.readLine()) != null) {
                result += line+"\n";
            }
            System.out.println(result);
  可以使用工具类IOUtils的toString方法获取响应结果.
           List list = IOUtils.readLines(entity.getContent(),"UTF-8");
            for(String s:list){
                System.out.println(s);
            }
   或者:
          result=IOUtils.toString(entity.getContent(),"utf-8");
   可以使用EntityUtils的toString方法获取响应结果.(推荐使用)
           if(entity!=null){
                System.out.println(EntityUtils.toString(entity));
            }

8).释放连接,无论执行方法是否成功,都必须释放连接

        EntityUtils.consume(httpEntity);
            closeableHttpClient.close();

完整代码:

package com.sc.http;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
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.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 HttpClientTest3 {

    public static void main(String[] args) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://123.58.251.183:8080/goods/UserServlet");
        List list = new ArrayList();
        list.add(new BasicNameValuePair("method","loginMobile"));
        list.add(new BasicNameValuePair("loginname","abc"));
        list.add(new BasicNameValuePair("loginpass","abc"));

         HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
          RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpEntity httpEntity = null;
        try {
            HttpEntity postEntity = new UrlEncodedFormEntity(list);
            post.setEntity(postEntity);
            //post.setConfig(config);

            CloseableHttpResponse reponse = closeableHttpClient.execute(post);
            httpEntity= reponse.getEntity();
            System.out.println(EntityUtils.toString(httpEntity, "utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                EntityUtils.consume(httpEntity);
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

你可能感兴趣的:(Java学习笔记 31 - 使用HTTP协议发送GET/POST请求(详细))