首页 > 技术文章 > java发送http的get、post请求

spiders 2016-09-01 13:45 原文

(转自http://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html)

Http请求类:

  1 package com.study.test;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStreamReader;
  6 import java.io.PrintWriter;
  7 import java.net.URL;
  8 import java.net.URLConnection;
  9 import java.util.List;
 10 import java.util.Map;
 11 
 12 public class HttpRequest {
 13     /**
 14      * 向指定URL发送GET方法的请求
 15      *
 16      * @param url   发送请求的URL
 17      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
 18      * @return URL 所代表远程资源的响应结果
 19      */
 20     public static String sendGet(String url, String param) {
 21         String result = "";
 22         BufferedReader in = null;
 23         try {
 24             String urlNameString = url + "?" + param;
 25             URL realUrl = new URL(urlNameString);
 26             // 打开和URL之间的连接
 27             URLConnection connection = realUrl.openConnection();
 28             // 设置通用的请求属性
 29             connection.setRequestProperty("accept", "*/*");
 30             connection.setRequestProperty("connection", "Keep-Alive");
 31             connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
 32             // 建立实际的连接
 33             connection.connect();
 34             // 获取所有响应头字段
 35             Map<String, List<String>> map = connection.getHeaderFields();
 36             // 遍历所有的响应头字段
 37             for (String key : map.keySet()) {
 38                 System.out.println(key + "--->" + map.get(key));
 39             }
 40             // 定义 BufferedReader输入流来读取URL的响应
 41             in = new BufferedReader(new InputStreamReader(
 42                     connection.getInputStream()));
 43             String line;
 44             while ((line = in.readLine()) != null) {
 45                 result += line;
 46             }
 47         } catch (Exception e) {
 48             System.out.println("发送GET请求出现异常!" + e);
 49             e.printStackTrace();
 50         }
 51         // 使用finally块来关闭输入流
 52         finally {
 53             try {
 54                 if (in != null) {
 55                     in.close();
 56                 }
 57             } catch (Exception e2) {
 58                 e2.printStackTrace();
 59             }
 60         }
 61         return result;
 62     }
 63 
 64     /**
 65      * 向指定 URL 发送POST方法的请求
 66      *
 67      * @param url   发送请求的 URL
 68      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
 69      * @return 所代表远程资源的响应结果
 70      */
 71     public static String sendPost(String url, String param) {
 72         PrintWriter out = null;
 73         BufferedReader in = null;
 74         String result = "";
 75         try {
 76             URL realUrl = new URL(url);
 77             // 打开和URL之间的连接
 78             URLConnection conn = realUrl.openConnection();
 79             // 设置通用的请求属性
 80             conn.setRequestProperty("accept", "*/*");
 81             conn.setRequestProperty("connection", "Keep-Alive");
 82             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
 83             // 发送POST请求必须设置如下两行
 84             conn.setDoOutput(true);
 85             conn.setDoInput(true);
 86             // 获取URLConnection对象对应的输出流
 87             out = new PrintWriter(conn.getOutputStream());
 88             // 发送请求参数
 89             out.print(param);
 90             // flush输出流的缓冲
 91             out.flush();
 92             // 定义BufferedReader输入流来读取URL的响应
 93             in = new BufferedReader(
 94                     new InputStreamReader(conn.getInputStream()));
 95             String line;
 96             while ((line = in.readLine()) != null) {
 97                 result += line;
 98             }
 99         } catch (Exception e) {
100             System.out.println("发送 POST 请求出现异常!" + e);
101             e.printStackTrace();
102         }
103         //使用finally块来关闭输出流、输入流
104         finally {
105             try {
106                 if (out != null) {
107                     out.close();
108                 }
109                 if (in != null) {
110                     in.close();
111                 }
112             } catch (IOException ex) {
113                 ex.printStackTrace();
114             }
115         }
116         return result;
117     }
118 }

调用方法:

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

        //发送 POST 请求
        String sr = HttpRequest.sendPost("http://localhost:8080/rings/receive", "key=123&v=456");
        System.out.println(sr);
    }

推荐阅读