Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 159|回复: 0

[默认分类] 通过java.net.URLConnection发送HTTP请求的方法

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-6-1 10:50:56 | 显示全部楼层 |阅读模式
    如何通过java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求。
    Java有原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,但不够简便;
    所以,也流行有许多Java HTTP请求的framework,如,Apache的HttpClient。
    目前项目主要用到Java原生的方式,所以,这里主要介绍此方式。
      
    运用原生Java Api发送简单的Get请求、Post请求

    HTTP请求粗分为两种,一种是GET请求,一种是POST请求。(详细的请见:Hypertext Transfer Protocol -- HTTP/1.1 - Method Definitions
    使用Java发送这两种请求的代码大同小异,只是一些参数设置的不同。步骤如下:

    通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)
    设置请求的参数
    发送请求
    以输入流的形式获取返回内容
    关闭输入流

      
    简单的Get请求示例如下:



      
    1. package com.nicchagil.httprequestdemo;
    2. import java.io.BufferedReader;
    3. import java.io.InputStream;
    4. import java.io.InputStreamReader;
    5. import java.net.HttpURLConnection;
    6. import java.net.URL;
    7. import java.net.URLConnection;
    8. public class HttpGetRequest {
    9.     /**
    10.      * Main
    11.      * @param args
    12.      * @throws Exception
    13.      */
    14.     public static void main(String[] args) throws Exception {
    15.         System.out.println(doGet());
    16.     }
    17.    
    18.     /**
    19.      * Get Request
    20.      * @return
    21.      * @throws Exception
    22.      */
    23.     public static String doGet() throws Exception {
    24.         URL localURL = new URL("http://localhost:8080/OneHttpServer/");
    25.         URLConnection connection = localURL.openConnection();
    26.         HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
    27.         
    28.         httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
    29.         httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    30.         
    31.         InputStream inputStream = null;
    32.         InputStreamReader inputStreamReader = null;
    33.         BufferedReader reader = null;
    34.         StringBuffer resultBuffer = new StringBuffer();
    35.         String tempLine = null;
    36.         
    37.         if (httpURLConnection.getResponseCode() >= 300) {
    38.             throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
    39.         }
    40.         
    41.         try {
    42.             inputStream = httpURLConnection.getInputStream();
    43.             inputStreamReader = new InputStreamReader(inputStream);
    44.             reader = new BufferedReader(inputStreamReader);
    45.             
    46.             while ((tempLine = reader.readLine()) != null) {
    47.                 resultBuffer.append(tempLine);
    48.             }
    49.             
    50.         } finally {
    51.             
    52.             if (reader != null) {
    53.                 reader.close();
    54.             }
    55.             
    56.             if (inputStreamReader != null) {
    57.                 inputStreamReader.close();
    58.             }
    59.             
    60.             if (inputStream != null) {
    61.                 inputStream.close();
    62.             }
    63.             
    64.         }
    65.         
    66.         return resultBuffer.toString();
    67.     }
    68.    
    69. }
    复制代码

      
    HttpGetRequest

      
    简单的Post请求示例如下:



      
    1. package com.nicchagil.httprequestdemo;
    2. import java.io.BufferedReader;
    3. import java.io.InputStream;
    4. import java.io.InputStreamReader;
    5. import java.io.OutputStream;
    6. import java.io.OutputStreamWriter;
    7. import java.net.HttpURLConnection;
    8. import java.net.URL;
    9. import java.net.URLConnection;
    10. public class HttpPostRequest {
    11.     /**
    12.      * Main
    13.      * @param args
    14.      * @throws Exception
    15.      */
    16.     public static void main(String[] args) throws Exception {
    17.         System.out.println(doPost());
    18.     }
    19.    
    20.     /**
    21.      * Post Request
    22.      * @return
    23.      * @throws Exception
    24.      */
    25.     public static String doPost() throws Exception {
    26.         String parameterData = "username=nickhuang&blog=http://www.cnblogs.com/nick-huang/";
    27.         
    28.         URL localURL = new URL("http://localhost:8080/OneHttpServer/");
    29.         URLConnection connection = localURL.openConnection();
    30.         HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
    31.         
    32.         httpURLConnection.setDoOutput(true);
    33.         httpURLConnection.setRequestMethod("POST");
    34.         httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
    35.         httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    36.         httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));
    37.         
    38.         OutputStream outputStream = null;
    39.         OutputStreamWriter outputStreamWriter = null;
    40.         InputStream inputStream = null;
    41.         InputStreamReader inputStreamReader = null;
    42.         BufferedReader reader = null;
    43.         StringBuffer resultBuffer = new StringBuffer();
    44.         String tempLine = null;
    45.         
    46.         try {
    47.             outputStream = httpURLConnection.getOutputStream();
    48.             outputStreamWriter = new OutputStreamWriter(outputStream);
    49.             
    50.             outputStreamWriter.write(parameterData.toString());
    51.             outputStreamWriter.flush();
    52.             
    53.             if (httpURLConnection.getResponseCode() >= 300) {
    54.                 throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
    55.             }
    56.             
    57.             inputStream = httpURLConnection.getInputStream();
    58.             inputStreamReader = new InputStreamReader(inputStream);
    59.             reader = new BufferedReader(inputStreamReader);
    60.             
    61.             while ((tempLine = reader.readLine()) != null) {
    62.                 resultBuffer.append(tempLine);
    63.             }
    64.             
    65.         } finally {
    66.             
    67.             if (outputStreamWriter != null) {
    68.                 outputStreamWriter.close();
    69.             }
    70.             
    71.             if (outputStream != null) {
    72.                 outputStream.close();
    73.             }
    74.             
    75.             if (reader != null) {
    76.                 reader.close();
    77.             }
    78.             
    79.             if (inputStreamReader != null) {
    80.                 inputStreamReader.close();
    81.             }
    82.             
    83.             if (inputStream != null) {
    84.                 inputStream.close();
    85.             }
    86.             
    87.         }
    88.         return resultBuffer.toString();
    89.     }
    90. }
    复制代码

      
    HttpPostRequest

      
    简单封装
    如果项目中有多处地方使用HTTP请求,我们适当对其进行封装,

    可以大大减少代码量(不需每次都写一大段原生的请求Source code)
    也可以使配置更灵活、方便(全局设置一些项目特有的配置,比如已商榷的time out时间、已确定的Proxy Server,避免以后改动繁琐)

      
    以下简单封装成HttpRequestor,以便使用:



      
    1. package com.nicchagil.util.httprequestor;
    2. import java.io.BufferedReader;
    3. import java.io.IOException;
    4. import java.io.InputStream;
    5. import java.io.InputStreamReader;
    6. import java.io.OutputStream;
    7. import java.io.OutputStreamWriter;
    8. import java.net.HttpURLConnection;
    9. import java.net.InetSocketAddress;
    10. import java.net.Proxy;
    11. import java.net.URL;
    12. import java.net.URLConnection;
    13. import java.util.Iterator;
    14. import java.util.Map;
    15. public class HttpRequestor {
    16.    
    17.     private String charset = "utf-8";
    18.     private Integer connectTimeout = null;
    19.     private Integer socketTimeout = null;
    20.     private String proxyHost = null;
    21.     private Integer proxyPort = null;
    22.    
    23.     /**
    24.      * Do GET request
    25.      * @param url
    26.      * @return
    27.      * @throws Exception
    28.      * @throws IOException
    29.      */
    30.     public String doGet(String url) throws Exception {
    31.         
    32.         URL localURL = new URL(url);
    33.         
    34.         URLConnection connection = openConnection(localURL);
    35.         HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
    36.         
    37.         httpURLConnection.setRequestProperty("Accept-Charset", charset);
    38.         httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    39.         
    40.         InputStream inputStream = null;
    41.         InputStreamReader inputStreamReader = null;
    42.         BufferedReader reader = null;
    43.         StringBuffer resultBuffer = new StringBuffer();
    44.         String tempLine = null;
    45.         
    46.         if (httpURLConnection.getResponseCode() >= 300) {
    47.             throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
    48.         }
    49.         
    50.         try {
    51.             inputStream = httpURLConnection.getInputStream();
    52.             inputStreamReader = new InputStreamReader(inputStream);
    53.             reader = new BufferedReader(inputStreamReader);
    54.             
    55.             while ((tempLine = reader.readLine()) != null) {
    56.                 resultBuffer.append(tempLine);
    57.             }
    58.             
    59.         } finally {
    60.             
    61.             if (reader != null) {
    62.                 reader.close();
    63.             }
    64.             
    65.             if (inputStreamReader != null) {
    66.                 inputStreamReader.close();
    67.             }
    68.             
    69.             if (inputStream != null) {
    70.                 inputStream.close();
    71.             }
    72.             
    73.         }
    74.         return resultBuffer.toString();
    75.     }
    76.    
    77.     /**
    78.      * Do POST request
    79.      * @param url
    80.      * @param parameterMap
    81.      * @return
    82.      * @throws Exception
    83.      */
    84.     public String doPost(String url, Map parameterMap) throws Exception {
    85.         
    86.         /* Translate parameter map to parameter date string */
    87.         StringBuffer parameterBuffer = new StringBuffer();
    88.         if (parameterMap != null) {
    89.             Iterator iterator = parameterMap.keySet().iterator();
    90.             String key = null;
    91.             String value = null;
    92.             while (iterator.hasNext()) {
    93.                 key = (String)iterator.next();
    94.                 if (parameterMap.get(key) != null) {
    95.                     value = (String)parameterMap.get(key);
    96.                 } else {
    97.                     value = "";
    98.                 }
    99.                
    100.                 parameterBuffer.append(key).append("=").append(value);
    101.                 if (iterator.hasNext()) {
    102.                     parameterBuffer.append("&");
    103.                 }
    104.             }
    105.         }
    106.         
    107.         System.out.println("POST parameter : " + parameterBuffer.toString());
    108.         
    109.         URL localURL = new URL(url);
    110.         
    111.         URLConnection connection = openConnection(localURL);
    112.         HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
    113.         
    114.         httpURLConnection.setDoOutput(true);
    115.         httpURLConnection.setRequestMethod("POST");
    116.         httpURLConnection.setRequestProperty("Accept-Charset", charset);
    117.         httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    118.         httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
    119.         
    120.         OutputStream outputStream = null;
    121.         OutputStreamWriter outputStreamWriter = null;
    122.         InputStream inputStream = null;
    123.         InputStreamReader inputStreamReader = null;
    124.         BufferedReader reader = null;
    125.         StringBuffer resultBuffer = new StringBuffer();
    126.         String tempLine = null;
    127.         
    128.         try {
    129.             outputStream = httpURLConnection.getOutputStream();
    130.             outputStreamWriter = new OutputStreamWriter(outputStream);
    131.             
    132.             outputStreamWriter.write(parameterBuffer.toString());
    133.             outputStreamWriter.flush();
    134.             
    135.             if (httpURLConnection.getResponseCode() >= 300) {
    136.                 throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
    137.             }
    138.             
    139.             inputStream = httpURLConnection.getInputStream();
    140.             inputStreamReader = new InputStreamReader(inputStream);
    141.             reader = new BufferedReader(inputStreamReader);
    142.             
    143.             while ((tempLine = reader.readLine()) != null) {
    144.                 resultBuffer.append(tempLine);
    145.             }
    146.             
    147.         } finally {
    148.             
    149.             if (outputStreamWriter != null) {
    150.                 outputStreamWriter.close();
    151.             }
    152.             
    153.             if (outputStream != null) {
    154.                 outputStream.close();
    155.             }
    156.             
    157.             if (reader != null) {
    158.                 reader.close();
    159.             }
    160.             
    161.             if (inputStreamReader != null) {
    162.                 inputStreamReader.close();
    163.             }
    164.             
    165.             if (inputStream != null) {
    166.                 inputStream.close();
    167.             }
    168.             
    169.         }
    170.         return resultBuffer.toString();
    171.     }
    172.     private URLConnection openConnection(URL localURL) throws IOException {
    173.         URLConnection connection;
    174.         if (proxyHost != null && proxyPort != null) {
    175.             Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
    176.             connection = localURL.openConnection(proxy);
    177.         } else {
    178.             connection = localURL.openConnection();
    179.         }
    180.         return connection;
    181.     }
    182.    
    183.     /**
    184.      * Render request according setting
    185.      * @param request
    186.      */
    187.     private void renderRequest(URLConnection connection) {
    188.         
    189.         if (connectTimeout != null) {
    190.             connection.setConnectTimeout(connectTimeout);
    191.         }
    192.         
    193.         if (socketTimeout != null) {
    194.             connection.setReadTimeout(socketTimeout);
    195.         }
    196.         
    197.     }
    198.     /*
    199.      * Getter & Setter
    200.      */
    201.     public Integer getConnectTimeout() {
    202.         return connectTimeout;
    203.     }
    204.     public void setConnectTimeout(Integer connectTimeout) {
    205.         this.connectTimeout = connectTimeout;
    206.     }
    207.     public Integer getSocketTimeout() {
    208.         return socketTimeout;
    209.     }
    210.     public void setSocketTimeout(Integer socketTimeout) {
    211.         this.socketTimeout = socketTimeout;
    212.     }
    213.     public String getProxyHost() {
    214.         return proxyHost;
    215.     }
    216.     public void setProxyHost(String proxyHost) {
    217.         this.proxyHost = proxyHost;
    218.     }
    219.     public Integer getProxyPort() {
    220.         return proxyPort;
    221.     }
    222.     public void setProxyPort(Integer proxyPort) {
    223.         this.proxyPort = proxyPort;
    224.     }
    225.     public String getCharset() {
    226.         return charset;
    227.     }
    228.     public void setCharset(String charset) {
    229.         this.charset = charset;
    230.     }
    231.    
    232. }
    复制代码

      
    HttpRequestor

       
    写一个调用的测试类:



      
    1. package com.nicchagil.util.httprequestor;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. public class Call {
    5.     public static void main(String[] args) throws Exception {
    6.         
    7.         /* Post Request */
    8.         Map dataMap = new HashMap();
    9.         dataMap.put("username", "Nick Huang");
    10.         dataMap.put("blog", "IT");
    11.         System.out.println(new HttpRequestor().doPost("http://localhost:8080/OneHttpServer/", dataMap));
    12.         
    13.         /* Get Request */
    14.         System.out.println(new HttpRequestor().doGet("http://localhost:8080/OneHttpServer/"));
    15.     }
    16. }
    复制代码

      
    Call

      
    OK,完成!!
      
    简单测试
    以上的请求地址都是http://localhost:8080/OneHttpServer/
    这是自己的一个用于测试的Web Application,就一个简单的Servlet和web.xml。毕竟需要测试请求参数是否能正常接收,处理超时的情况。
    LoginServlet



      
    1. import java.io.IOException;
    2. import javax.servlet.ServletException;
    3. import javax.servlet.http.HttpServlet;
    4. import javax.servlet.http.HttpServletRequest;
    5. import javax.servlet.http.HttpServletResponse;
    6. public class LoginServlet extends HttpServlet {
    7.     private static final long serialVersionUID = 1L;
    8.       
    9.     public LoginServlet() {
    10.         super();
    11.     }
    12.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    13.         this.doPost(request, response);
    14.     }
    15.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    16.         String username = request.getParameter("username");
    17.         String blog = request.getParameter("blog");
    18.         
    19.         System.out.println(username);
    20.         System.out.println(blog);
    21.         
    22.         response.setContentType("text/plain; charset=UTF-8");
    23.         response.setCharacterEncoding("UTF-8");
    24.         response.getWriter().write("It is ok!");
    25.     }
    26. }
    复制代码

      
    LoginServlet

      
    web.xml



      
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    3.   <display-name>OneHttpServer</display-name>
    4.   <welcome-file-list>
    5.     <welcome-file>LoginServlet</welcome-file>
    6.   </welcome-file-list>
    7.   
    8.   <servlet>
    9.     <description></description>
    10.     <display-name>LoginServlet</display-name>
    11.     <servlet-name>LoginServlet</servlet-name>
    12.     <servlet-class>LoginServlet</servlet-class>
    13.   </servlet>
    14.   <servlet-mapping>
    15.     <servlet-name>LoginServlet</servlet-name>
    16.     <url-pattern>/LoginServlet</url-pattern>
    17.   </servlet-mapping>
    18.   
    19. </web-app>
    复制代码

      
    web.xml

      
    感觉自己萌萌哒!~~
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-25 03:26 , Processed in 0.497954 second(s), 48 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表