【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法

Java原生的API可用于发送HTTP请求

即java.net.URL、java.net.URLConnection,JDK自带的类;

1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)

2.设置请求的参数

3.发送请求

4.以输入流的形式获取返回内容

5.关闭输入流

  • 封装请求类

      1 package com.util;
      2
      3 import java.io.BufferedReader;
      4 import java.io.IOException;
      5 import java.io.InputStream;
      6 import java.io.InputStreamReader;
      7 import java.io.OutputStream;
      8 import java.io.OutputStreamWriter;
      9 import java.net.HttpURLConnection;
     10 import java.net.MalformedURLException;
     11 import java.net.URL;
     12 import java.net.URLConnection;
     13 import java.util.Iterator;
     14 import java.util.Map;
     15
     16
     17
     18 /**
     19  * Java原生的API可用于发送HTTP请求
     20  * 即java.net.URL、java.net.URLConnection,JDK自带的类;
     21  *
     22  * 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)
     23  * 2.设置请求的参数
     24  * 3.发送请求
     25  * 4.以输入流的形式获取返回内容
     26  * 5.关闭输入流
     27  *
     28  * @author H__D
     29  *
     30  */
     31 public class HttpRequestor  {
     32
     33     //post请求
     34     public static final String HTTP_POST = "POST";
     35
     36     //get请求
     37     public static final String HTTP_GET = "GET";
     38
     39     // utf-8字符编码
     40     public static final String CHARSET_UTF_8 = "utf-8";
     41
     42     // HTTP内容类型。如果未指定ContentType,默认为TEXT/HTML
     43     public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";
     44
     45     // HTTP内容类型。相当于form表单的形式,提交暑假
     46     public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";
     47
     48     //请求超时时间
     49     public static final int SEND_REQUEST_TIME_OUT = 5000;
     50
     51     //将读超时时间
     52     public static final int READ_TIME_OUT = 5000;
     53
     54
     55     /**
     56      * http请求的主要方法
     57      * @param requestType 请求类型
     58      * @param urlStr 请求地址
     59      * @param body 请求发送内容
     60      * @return 返回内容
     61      */
     62     public static String requestMethod(String requestType,String urlStr,String body) {
     63
     64         //是否有http正文提交
     65         boolean isDoInput = false;
     66         if(body != null && body.length() > 0) isDoInput = true;
     67         OutputStream outputStream = null;
     68         OutputStreamWriter outputStreamWriter = null;
     69         InputStream inputStream = null;
     70         InputStreamReader inputStreamReader = null;
     71         BufferedReader reader = null;
     72         StringBuffer resultBuffer = new StringBuffer();
     73         String tempLine = null;
     74         try {
     75             // 统一资源
     76             URL url = new URL(urlStr);
     77             // 连接类的父类,抽象类
     78             URLConnection urlConnection = url.openConnection();
     79             // http的连接类
     80             HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
     81
     82
     83             // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
     84             // http正文内,因此需要设为true, 默认情况下是false;
     85             if(isDoInput){
     86                 httpURLConnection.setDoOutput(true);
     87                 httpURLConnection.setRequestProperty("Content-Length", String.valueOf(body.length()));
     88             }
     89             // 设置是否从httpUrlConnection读入,默认情况下是true;
     90             httpURLConnection.setDoInput(true);
     91             //设置一个指定的超时值(以毫秒为单位)
     92             httpURLConnection.setConnectTimeout(SEND_REQUEST_TIME_OUT);
     93             //将读超时设置为指定的超时,以毫秒为单位。
     94             httpURLConnection.setReadTimeout(READ_TIME_OUT);
     95             // Post 请求不能使用缓存
     96             httpURLConnection.setUseCaches(false);
     97             //设置字符编码
     98             httpURLConnection.setRequestProperty("Accept-Charset", CHARSET_UTF_8);
     99             //设置内容类型
    100             httpURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE_FORM_URL);
    101             // 设定请求的方法,默认是GET
    102             httpURLConnection.setRequestMethod(requestType);
    103
    104             //打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
    105             //如果在已打开连接(此时 connected 字段的值为 true)的情况下调用 connect 方法,则忽略该调用。
    106             httpURLConnection.connect();
    107
    108             if(isDoInput){
    109                 outputStream = httpURLConnection.getOutputStream();
    110                 outputStreamWriter = new OutputStreamWriter(outputStream);
    111                 outputStreamWriter.write(body);
    112                 outputStreamWriter.flush();// 刷新
    113             }
    114             if (httpURLConnection.getResponseCode() >= 300) {
    115                 throw new Exception(
    116                         "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
    117             }
    118
    119             if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    120                 inputStream = httpURLConnection.getInputStream();
    121                 inputStreamReader = new InputStreamReader(inputStream);
    122                 reader = new BufferedReader(inputStreamReader);
    123
    124                 while ((tempLine = reader.readLine()) != null) {
    125                     resultBuffer.append(tempLine);
    126                     resultBuffer.append("\n");
    127                 }
    128             }
    129
    130         } catch (MalformedURLException e) {
    131             // TODO Auto-generated catch block
    132             e.printStackTrace();
    133         } catch (IOException e) {
    134             // TODO Auto-generated catch block
    135             e.printStackTrace();
    136         } catch (Exception e) {
    137             // TODO Auto-generated catch block
    138             e.printStackTrace();
    139         } finally {//关闭流
    140
    141             try {
    142                 if (outputStreamWriter != null) {
    143                     outputStreamWriter.close();
    144                 }
    145             } catch (Exception e) {
    146                 // TODO Auto-generated catch block
    147                 e.printStackTrace();
    148             }
    149             try {
    150                 if (outputStream != null) {
    151                     outputStream.close();
    152                 }
    153             } catch (Exception e) {
    154                 // TODO Auto-generated catch block
    155                 e.printStackTrace();
    156             }
    157             try {
    158                 if (reader != null) {
    159                     reader.close();
    160                 }
    161             } catch (Exception e) {
    162                 // TODO Auto-generated catch block
    163                 e.printStackTrace();
    164             }
    165             try {
    166                 if (inputStreamReader != null) {
    167                     inputStreamReader.close();
    168                 }
    169             } catch (Exception e) {
    170                 // TODO Auto-generated catch block
    171                 e.printStackTrace();
    172             }
    173             try {
    174                 if (inputStream != null) {
    175                     inputStream.close();
    176                 }
    177             } catch (Exception e) {
    178                 // TODO Auto-generated catch block
    179                 e.printStackTrace();
    180             }
    181         }
    182         return resultBuffer.toString();
    183     }
    184
    185     /**
    186      * 将map集合的键值对转化成:key1=value1&key2=value2 的形式
    187      * @param parameterMap 需要转化的键值对集合
    188      * @return 字符串
    189      */
    190     public static String convertStringParamter(Map parameterMap ){
    191         StringBuffer parameterBuffer = new StringBuffer();
    192         if (parameterMap != null) {
    193             Iterator iterator = parameterMap.keySet().iterator();
    194             String key = null;
    195             String value = null;
    196             while (iterator.hasNext()) {
    197                 key = (String)iterator.next();
    198                 if (parameterMap.get(key) != null) {
    199                     value = (String)parameterMap.get(key);
    200                 } else {
    201                     value = "";
    202                 }
    203                 parameterBuffer.append(key).append("=").append(value);
    204                 if (iterator.hasNext()) {
    205                     parameterBuffer.append("&");
    206                 }
    207             }
    208         }
    209         return parameterBuffer.toString();
    210     }
    211
    212
    213
    214
    215     public static void main(String[] args) throws MalformedURLException {
    216
    217          System.out.println(requestMethod(HTTP_GET, "http://127.0.0.1:8080/test/TestHttpRequestServlet", "username=123&password=我是谁"));
    218
    219     }
    220
    221 }

    HttpRequestor

  • 测试Servlet

     1 package com.servlet;
     2
     3 import java.io.IOException;
     4
     5 import javax.servlet.ServletException;
     6 import javax.servlet.http.HttpServlet;
     7 import javax.servlet.http.HttpServletRequest;
     8 import javax.servlet.http.HttpServletResponse;
     9
    10 public class TestHttpRequestServelt extends HttpServlet {
    11
    12
    13     @Override
    14     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    15
    16         System.out.println("this is a TestHttpRequestServlet");
    17         request.setCharacterEncoding("utf-8");
    18
    19         String username = request.getParameter("username");
    20         String password = request.getParameter("password");
    21
    22         System.out.println(username);
    23         System.out.println(password);
    24
    25         response.setContentType("text/plain; charset=UTF-8");
    26         response.setCharacterEncoding("UTF-8");
    27         response.getWriter().write("This is ok!");
    28
    29     }
    30 }

    TestHttpRequestServelt

  • web.xml配置

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
     3   <display-name>test</display-name>
     4
     5   <servlet>
     6       <servlet-name>TestHttpRequestServlet</servlet-name>
     7       <servlet-class>com.servlet.TestHttpRequestServelt</servlet-class>
     8   </servlet>
     9
    10   <servlet-mapping>
    11       <servlet-name>TestHttpRequestServlet</servlet-name>
    12       <url-pattern>/TestHttpRequestServlet</url-pattern>
    13   </servlet-mapping>
    14
    15   <welcome-file-list>
    16     <welcome-file>index.html</welcome-file>
    17     <welcome-file>index.htm</welcome-file>
    18     <welcome-file>index.jsp</welcome-file>
    19     <welcome-file>default.html</welcome-file>
    20     <welcome-file>default.htm</welcome-file>
    21     <welcome-file>default.jsp</welcome-file>
    22   </welcome-file-list>
    23 </web-app>

    web.xml

时间: 2024-08-09 16:55:15

【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法的相关文章

使用httpclient实现http链接池与使用HttpURLConnection发送http请求的方法与性能对比

使用httpclient实现http链接池与使用HttpURLConnection发送http请求的方法与性能对比 在项目中需要使用http调用接口,实现了两套发送http请求的方法,一个是使用apache的httpclient提供的http链接池来发送http请求,另一个是使用java原生的HttpURLConnection来发送http请求,并对两者性能进行了对比. 使用httpclient中的链接池发送http请求 使用最新的4.5.2版httpclient进行实现.在maven中引入 <

【JAVA】通过HttpClient发送HTTP请求的方法

HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 嵌入在 HTML 页面中的javascript 代码,猜测内容类型,重新格式化请求/重定向URI,或者其它和 HTTP 运输无关的功能. HttpClient使用 使用需要引入jar包,maven项目引入如下: 1 <dependency> 2 <groupId>org.apache

java 使用原生HttpURLConnection发送post请求

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Cale

通过java.net.URLConnection发送HTTP请求的方法

1.GET与POST请求的区别 a) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet, b) post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内. 2.URLConnection的对象 a) 获取URLConnection实例 URL url = new URL(urlString); // 根据url生成urlConnection对象 urlConnection = (HttpURLConnection) url.

java 常见几种发送http请求案例

1 import java.io.FileOutputStream; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.InputStreamReader; 5 import java.io.OutputStreamWriter; 6 import java.io.UnsupportedEncodingException; 7 import java.net.HttpURLConnection

HttpUrlConnection发送url请求(后台springmvc)

1.HttpURLConnection发送url请求 public class JavaRequest { private static final String BASE_URL = "http://localhost:8080/dsdemo/"; public static String userToken = null; public static String problemName = null; public static String sendPost(String su

java 短信猫发送短信的方法

用java实现短信收发的功能,目前一般项目中短信群发功能的实现方法大致有下面三种: ·                 1. 向运行商申请短信网关,不需要额外的设备,利用运行商提供的API调用程序发送短信,适用于大型的通信公司. ·                 2. 借助像GSM MODEM之类的设备(支持AT指令的手机也行),通过数据线连接电脑来发送短信,这种方法比较适用于小公司及个人.要实现这种方式必须理解串口通信.AT指令.短信编码.解码. ·                 3. 借

java中原生的发送http请求(无任何的jar包导入)

1 package com.teamsun.pay.wxpay.util; 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;

JAVA使用原始HttpURLConnection发送POST数据

package com.newflypig.demo; /** * 使用jdk自带的HttpURLConnection向URL发送POST请求并输出响应结果 * 参数使用流传递,并且硬编码为字符串"name=XXX"的格式 */ import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnectio