【JAVA】經過URLConnection/HttpURLConnection發送HTTP請求的方法(一)

 Java原生的API可用於發送HTTP請求html

 即java.net.URL、java.net.URLConnection,JDK自帶的類;java

 

 1.經過統一資源定位器(java.net.URL)獲取鏈接器(java.net.URLConnection)web

 2.設置請求的參數緩存

 3.發送請求app

 4.以輸入流的形式獲取返回內容jsp

 5.關閉輸入流ide

  • 封裝請求類
      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 public class HttpConnectionUtil {
     17 
     18     // post請求
     19     public static final String HTTP_POST = "POST";
     20 
     21     // get請求
     22     public static final String HTTP_GET = "GET";
     23 
     24     // utf-8字符編碼
     25     public static final String CHARSET_UTF_8 = "utf-8";
     26 
     27     // HTTP內容類型。若是未指定ContentType,默認爲TEXT/HTML
     28     public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";
     29 
     30     // HTTP內容類型。至關於form表單的形式,提交暑假
     31     public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";
     32 
     33     // 請求超時時間
     34     public static final int SEND_REQUEST_TIME_OUT = 50000;
     35 
     36     // 將讀超時時間
     37     public static final int READ_TIME_OUT = 50000;
     38 
     39     /**
     40      * 
     41      * @param requestType
     42      *            請求類型
     43      * @param urlStr
     44      *            請求地址
     45      * @param body
     46      *            請求發送內容
     47      * @return 返回內容
     48      */
     49     public static String requestMethod(String requestType, String urlStr, String body) {
     50 
     51         // 是否有http正文提交
     52         boolean isDoInput = false;
     53         if (body != null && body.length() > 0)
     54             isDoInput = true;
     55         OutputStream outputStream = null;
     56         OutputStreamWriter outputStreamWriter = null;
     57         InputStream inputStream = null;
     58         InputStreamReader inputStreamReader = null;
     59         BufferedReader reader = null;
     60         StringBuffer resultBuffer = new StringBuffer();
     61         String tempLine = null;
     62         try {
     63             // 統一資源
     64             URL url = new URL(urlStr);
     65             // 鏈接類的父類,抽象類
     66             URLConnection urlConnection = url.openConnection();
     67             // http的鏈接類
     68             HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
     69 
     70             // 設置是否向httpUrlConnection輸出,由於這個是post請求,參數要放在
     71             // http正文內,所以須要設爲true, 默認狀況下是false;
     72             if (isDoInput) {
     73                 httpURLConnection.setDoOutput(true);
     74                 httpURLConnection.setRequestProperty("Content-Length", String.valueOf(body.length()));
     75             }
     76             // 設置是否從httpUrlConnection讀入,默認狀況下是true;
     77             httpURLConnection.setDoInput(true);
     78             // 設置一個指定的超時值(以毫秒爲單位)
     79             httpURLConnection.setConnectTimeout(SEND_REQUEST_TIME_OUT);
     80             // 將讀超時設置爲指定的超時,以毫秒爲單位。
     81             httpURLConnection.setReadTimeout(READ_TIME_OUT);
     82             // Post 請求不能使用緩存
     83             httpURLConnection.setUseCaches(false);
     84             // 設置字符編碼
     85             httpURLConnection.setRequestProperty("Accept-Charset", CHARSET_UTF_8);
     86             // 設置內容類型
     87             httpURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE_FORM_URL);
     88             // 設定請求的方法,默認是GET
     89             httpURLConnection.setRequestMethod(requestType);
     90 
     91             // 打開到此 URL 引用的資源的通訊連接(若是還沒有創建這樣的鏈接)。
     92             // 若是在已打開鏈接(此時 connected 字段的值爲 true)的狀況下調用 connect 方法,則忽略該調用。
     93             httpURLConnection.connect();
     94 
     95             if (isDoInput) {
     96                 outputStream = httpURLConnection.getOutputStream();
     97                 outputStreamWriter = new OutputStreamWriter(outputStream);
     98                 outputStreamWriter.write(body);
     99                 outputStreamWriter.flush();// 刷新
    100             }
    101             if (httpURLConnection.getResponseCode() >= 300) {
    102                 throw new Exception(
    103                         "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
    104             }
    105 
    106             if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    107                 inputStream = httpURLConnection.getInputStream();
    108                 inputStreamReader = new InputStreamReader(inputStream);
    109                 reader = new BufferedReader(inputStreamReader);
    110 
    111                 while ((tempLine = reader.readLine()) != null) {
    112                     resultBuffer.append(tempLine);
    113                     resultBuffer.append("\n");
    114                 }
    115             }
    116 
    117         } catch (MalformedURLException e) {
    118             // TODO Auto-generated catch block
    119             e.printStackTrace();
    120         } catch (IOException e) {
    121             // TODO Auto-generated catch block
    122             e.printStackTrace();
    123         } catch (Exception e) {
    124             // TODO Auto-generated catch block
    125             e.printStackTrace();
    126         } finally {// 關閉流
    127 
    128             try {
    129                 if (outputStreamWriter != null) {
    130                     outputStreamWriter.close();
    131                 }
    132             } catch (Exception e) {
    133                 // TODO Auto-generated catch block
    134                 e.printStackTrace();
    135             }
    136             try {
    137                 if (outputStream != null) {
    138                     outputStream.close();
    139                 }
    140             } catch (Exception e) {
    141                 // TODO Auto-generated catch block
    142                 e.printStackTrace();
    143             }
    144             try {
    145                 if (reader != null) {
    146                     reader.close();
    147                 }
    148             } catch (Exception e) {
    149                 // TODO Auto-generated catch block
    150                 e.printStackTrace();
    151             }
    152             try {
    153                 if (inputStreamReader != null) {
    154                     inputStreamReader.close();
    155                 }
    156             } catch (Exception e) {
    157                 // TODO Auto-generated catch block
    158                 e.printStackTrace();
    159             }
    160             try {
    161                 if (inputStream != null) {
    162                     inputStream.close();
    163                 }
    164             } catch (Exception e) {
    165                 // TODO Auto-generated catch block
    166                 e.printStackTrace();
    167             }
    168         }
    169         return resultBuffer.toString();
    170     }
    171 
    172     /**
    173      * 將map集合的鍵值對轉化成:key1=value1&key2=value2 的形式
    174      * 
    175      * @param parameterMap
    176      *            須要轉化的鍵值對集合
    177      * @return 字符串
    178      */
    179     public static String convertStringParamter(Map parameterMap) {
    180         StringBuffer parameterBuffer = new StringBuffer();
    181         if (parameterMap != null) {
    182             Iterator iterator = parameterMap.keySet().iterator();
    183             String key = null;
    184             String value = null;
    185             while (iterator.hasNext()) {
    186                 key = (String) iterator.next();
    187                 if (parameterMap.get(key) != null) {
    188                     value = (String) parameterMap.get(key);
    189                 } else {
    190                     value = "";
    191                 }
    192                 parameterBuffer.append(key).append("=").append(value);
    193                 if (iterator.hasNext()) {
    194                     parameterBuffer.append("&");
    195                 }
    196             }
    197         }
    198         return parameterBuffer.toString();
    199     }
    200 
    201     public static void main(String[] args) throws MalformedURLException {
    202 
    203         System.out.println(requestMethod(HTTP_GET, "http://127.0.0.1:8080/test/TestHttpRequestServlet",
    204                 "username=123&password=我是誰"));
    205 
    206     }
    207 }
    HttpConnectionUtil

     

  • 測試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
相關文章
相關標籤/搜索