JAVA发送HTTP请求经典收藏

2024-05-13 13:38

本文主要是介绍JAVA发送HTTP请求经典收藏,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

JDK 中提供了一些对无状态协议请求(HTTP )的支持,下面我就将我所写的一个小例子(组件)进行描述:

 首先让我们先构建一个请求类(HttpRequester )。

该类封装了 JAVA 实现简单请求的代码,如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.InputStreamReader;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7. import java.nio.charset.Charset;  
  8. import java.util.Map;  
  9. import java.util.Vector;  
  10.    
  11. /** 
  12.  * HTTP请求对象 
  13.  *  
  14.  * @author YYmmiinngg 
  15.  */  
  16. public class HttpRequester {  
  17.     private String defaultContentEncoding;  
  18.    
  19.     public HttpRequester() {  
  20.         this.defaultContentEncoding = Charset.defaultCharset().name();  
  21.     }  
  22.    
  23.     /** 
  24.      * 发送GET请求 
  25.      *  
  26.      * @param urlString 
  27.      *            URL地址 
  28.      * @return 响应对象 
  29.      * @throws IOException 
  30.      */  
  31.     public HttpRespons sendGet(String urlString) throws IOException {  
  32.         return this.send(urlString, "GET"nullnull);  
  33.     }  
  34.    
  35.     /** 
  36.      * 发送GET请求 
  37.      *  
  38.      * @param urlString 
  39.      *            URL地址 
  40.      * @param params 
  41.      *            参数集合 
  42.      * @return 响应对象 
  43.      * @throws IOException 
  44.      */  
  45.     public HttpRespons sendGet(String urlString, Map<String, String> params)  
  46.             throws IOException {  
  47.         return this.send(urlString, "GET", params, null);  
  48.     }  
  49.    
  50.     /** 
  51.      * 发送GET请求 
  52.      *  
  53.      * @param urlString 
  54.      *            URL地址 
  55.      * @param params 
  56.      *            参数集合 
  57.      * @param propertys 
  58.      *            请求属性 
  59.      * @return 响应对象 
  60.      * @throws IOException 
  61.      */  
  62.     public HttpRespons sendGet(String urlString, Map<String, String> params,  
  63.             Map<String, String> propertys) throws IOException {  
  64.         return this.send(urlString, "GET", params, propertys);  
  65.     }  
  66.    
  67.     /** 
  68.      * 发送POST请求 
  69.      *  
  70.      * @param urlString 
  71.      *            URL地址 
  72.      * @return 响应对象 
  73.      * @throws IOException 
  74.      */  
  75.     public HttpRespons sendPost(String urlString) throws IOException {  
  76.         return this.send(urlString, "POST"nullnull);  
  77.     }  
  78.    
  79.     /** 
  80.      * 发送POST请求 
  81.      *  
  82.      * @param urlString 
  83.      *            URL地址 
  84.      * @param params 
  85.      *            参数集合 
  86.      * @return 响应对象 
  87.      * @throws IOException 
  88.      */  
  89.     public HttpRespons sendPost(String urlString, Map<String, String> params)  
  90.             throws IOException {  
  91.         return this.send(urlString, "POST", params, null);  
  92.     }  
  93.    
  94.     /** 
  95.      * 发送POST请求 
  96.      *  
  97.      * @param urlString 
  98.      *            URL地址 
  99.      * @param params 
  100.      *            参数集合 
  101.      * @param propertys 
  102.      *            请求属性 
  103.      * @return 响应对象 
  104.      * @throws IOException 
  105.      */  
  106.     public HttpRespons sendPost(String urlString, Map<String, String> params,  
  107.             Map<String, String> propertys) throws IOException {  
  108.         return this.send(urlString, "POST", params, propertys);  
  109.     }  
  110.    
  111.     /** 
  112.      * 发送HTTP请求 
  113.      *  
  114.      * @param urlString 
  115.      * @return 响映对象 
  116.      * @throws IOException 
  117.      */  
  118.     private HttpRespons send(String urlString, String method,  
  119.             Map<String, String> parameters, Map<String, String> propertys)  
  120.             throws IOException {  
  121.         HttpURLConnection urlConnection = null;  
  122.    
  123.         if (method.equalsIgnoreCase("GET") && parameters != null) {  
  124.             StringBuffer param = new StringBuffer();  
  125.             int i = 0;  
  126.             for (String key : parameters.keySet()) {  
  127.                 if (i == 0)  
  128.                     param.append("?");  
  129.                 else  
  130.                     param.append("&");  
  131.                 param.append(key).append("=").append(parameters.get(key));  
  132.                 i++;  
  133.             }  
  134.             urlString += param;  
  135.         }  
  136.         URL url = new URL(urlString);  
  137.         urlConnection = (HttpURLConnection) url.openConnection();  
  138.    
  139.         urlConnection.setRequestMethod(method);  
  140.         urlConnection.setDoOutput(true);  
  141.         urlConnection.setDoInput(true);  
  142.         urlConnection.setUseCaches(false);  
  143.    
  144.         if (propertys != null)  
  145.             for (String key : propertys.keySet()) {  
  146.                 urlConnection.addRequestProperty(key, propertys.get(key));  
  147.             }  
  148.    
  149.         if (method.equalsIgnoreCase("POST") && parameters != null) {  
  150.             StringBuffer param = new StringBuffer();  
  151.             for (String key : parameters.keySet()) {  
  152.                 param.append("&");  
  153.                 param.append(key).append("=").append(parameters.get(key));  
  154.             }  
  155.             urlConnection.getOutputStream().write(param.toString().getBytes());  
  156.             urlConnection.getOutputStream().flush();  
  157.             urlConnection.getOutputStream().close();  
  158.         }  
  159.    
  160.         return this.makeContent(urlString, urlConnection);  
  161.     }  
  162.    
  163.     /** 
  164.      * 得到响应对象 
  165.      *  
  166.      * @param urlConnection 
  167.      * @return 响应对象 
  168.      * @throws IOException 
  169.      */  
  170.     private HttpRespons makeContent(String urlString,  
  171.             HttpURLConnection urlConnection) throws IOException {  
  172.         HttpRespons httpResponser = new HttpRespons();  
  173.         try {  
  174.             InputStream in = urlConnection.getInputStream();  
  175.             BufferedReader bufferedReader = new BufferedReader(  
  176.                     new InputStreamReader(in));  
  177.             httpResponser.contentCollection = new Vector<String>();  
  178.             StringBuffer temp = new StringBuffer();  
  179.             String line = bufferedReader.readLine();  
  180.             while (line != null) {  
  181.                 httpResponser.contentCollection.add(line);  
  182.                 temp.append(line).append("\r\n");  
  183.                 line = bufferedReader.readLine();  
  184.             }  
  185.             bufferedReader.close();  
  186.    
  187.             String ecod = urlConnection.getContentEncoding();  
  188.             if (ecod == null)  
  189.                 ecod = this.defaultContentEncoding;  
  190.    
  191.             httpResponser.urlString = urlString;  
  192.    
  193.             httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();  
  194.             httpResponser.file = urlConnection.getURL().getFile();  
  195.             httpResponser.host = urlConnection.getURL().getHost();  
  196.             httpResponser.path = urlConnection.getURL().getPath();  
  197.             httpResponser.port = urlConnection.getURL().getPort();  
  198.             httpResponser.protocol = urlConnection.getURL().getProtocol();  
  199.             httpResponser.query = urlConnection.getURL().getQuery();  
  200.             httpResponser.ref = urlConnection.getURL().getRef();  
  201.             httpResponser.userInfo = urlConnection.getURL().getUserInfo();  
  202.    
  203.             httpResponser.content = new String(temp.toString().getBytes(), ecod);  
  204.             httpResponser.contentEncoding = ecod;  
  205.             httpResponser.code = urlConnection.getResponseCode();  
  206.             httpResponser.message = urlConnection.getResponseMessage();  
  207.             httpResponser.contentType = urlConnection.getContentType();  
  208.             httpResponser.method = urlConnection.getRequestMethod();  
  209.             httpResponser.connectTimeout = urlConnection.getConnectTimeout();  
  210.             httpResponser.readTimeout = urlConnection.getReadTimeout();  
  211.    
  212.             return httpResponser;  
  213.         } catch (IOException e) {  
  214.             throw e;  
  215.         } finally {  
  216.             if (urlConnection != null)  
  217.                 urlConnection.disconnect();  
  218.         }  
  219.     }  
  220.    
  221.     /** 
  222.      * 默认的响应字符集 
  223.      */  
  224.     public String getDefaultContentEncoding() {  
  225.         return this.defaultContentEncoding;  
  226.     }  
  227.    
  228.     /** 
  229.      * 设置默认的响应字符集 
  230.      */  
  231.     public void setDefaultContentEncoding(String defaultContentEncoding) {  
  232.         this.defaultContentEncoding = defaultContentEncoding;  
  233.     }  
  234. }  


 

 

其次我们来看看响应对象(HttpRespons )。  响应对象其实只是一个数据BEAN ,由此来封装请求响应的结果数据,如下:

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import java.util.Vector;  
  2.    
  3. /** 
  4.  * 响应对象 
  5.  */  
  6. public class HttpRespons {  
  7.    
  8.     String urlString;  
  9.    
  10.     int defaultPort;  
  11.    
  12.     String file;  
  13.    
  14.     String host;  
  15.    
  16.     String path;  
  17.    
  18.     int port;  
  19.    
  20.     String protocol;  
  21.    
  22.     String query;  
  23.    
  24.     String ref;  
  25.    
  26.     String userInfo;  
  27.    
  28.     String contentEncoding;  
  29.    
  30.     String content;  
  31.    
  32.     String contentType;  
  33.    
  34.     int code;  
  35.    
  36.     String message;  
  37.    
  38.     String method;  
  39.    
  40.     int connectTimeout;  
  41.    
  42.     int readTimeout;  
  43.    
  44.     Vector<String> contentCollection;  
  45.    
  46.     public String getContent() {  
  47.         return content;  
  48.     }  
  49.    
  50.     public String getContentType() {  
  51.         return contentType;  
  52.     }  
  53.    
  54.     public int getCode() {  
  55.         return code;  
  56.     }  
  57.    
  58.     public String getMessage() {  
  59.         return message;  
  60.     }  
  61.    
  62.     public Vector<String> getContentCollection() {  
  63.         return contentCollection;  
  64.     }  
  65.    
  66.     public String getContentEncoding() {  
  67.         return contentEncoding;  
  68.     }  
  69.    
  70.     public String getMethod() {  
  71.         return method;  
  72.     }  
  73.    
  74.     public int getConnectTimeout() {  
  75.         return connectTimeout;  
  76.     }  
  77.    
  78.     public int getReadTimeout() {  
  79.         return readTimeout;  
  80.     }  
  81.    
  82.     public String getUrlString() {  
  83.         return urlString;  
  84.     }  
  85.    
  86.     public int getDefaultPort() {  
  87.         return defaultPort;  
  88.     }  
  89.    
  90.     public String getFile() {  
  91.         return file;  
  92.     }  
  93.    
  94.     public String getHost() {  
  95.         return host;  
  96.     }  
  97.    
  98.     public String getPath() {  
  99.         return path;  
  100.     }  
  101.    
  102.     public int getPort() {  
  103.         return port;  
  104.     }  
  105.    
  106.     public String getProtocol() {  
  107.         return protocol;  
  108.     }  
  109.    
  110.     public String getQuery() {  
  111.         return query;  
  112.     }  
  113.    
  114.     public String getRef() {  
  115.         return ref;  
  116.     }  
  117.    
  118.     public String getUserInfo() {  
  119.         return userInfo;  
  120.     }  
  121.    
  122. }  

 

最后,让我们写一个应用类,测试以上代码是否正确

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import com.yao.http.HttpRequester;  
  2. import com.yao.http.HttpRespons;  
  3.    
  4. public class Test {  
  5.     public static void main(String[] args) {  
  6.         try {  
  7.             HttpRequester request = new HttpRequester();  
  8.             HttpRespons hr = request.sendGet("http://www.csdn.net");  
  9.    
  10.             System.out.println(hr.getUrlString());  
  11.             System.out.println(hr.getProtocol());  
  12.             System.out.println(hr.getHost());  
  13.             System.out.println(hr.getPort());  
  14.             System.out.println(hr.getContentEncoding());  
  15.             System.out.println(hr.getMethod());  
  16.               
  17.             System.out.println(hr.getContent());  
  18.    
  19.         } catch (Exception e) {  
  20.             e.printStackTrace();  
  21.         }  
  22.     }  
  23. }

这篇关于JAVA发送HTTP请求经典收藏的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/985854

相关文章

Java实现字符串大小写转换的常用方法

《Java实现字符串大小写转换的常用方法》在Java中,字符串大小写转换是文本处理的核心操作之一,Java提供了多种灵活的方式来实现大小写转换,适用于不同场景和需求,本文将全面解析大小写转换的各种方法... 目录前言核心转换方法1.String类的基础方法2. 考虑区域设置的转换3. 字符级别的转换高级转换

SpringBoot简单整合ElasticSearch实践

《SpringBoot简单整合ElasticSearch实践》Elasticsearch支持结构化和非结构化数据检索,通过索引创建和倒排索引文档,提高搜索效率,它基于Lucene封装,分为索引库、类型... 目录一:ElasticSearch支持对结构化和非结构化的数据进行检索二:ES的核心概念Index:

Java方法重载与重写之同名方法的双面魔法(最新整理)

《Java方法重载与重写之同名方法的双面魔法(最新整理)》文章介绍了Java中的方法重载Overloading和方法重写Overriding的区别联系,方法重载是指在同一个类中,允许存在多个方法名相同... 目录Java方法重载与重写:同名方法的双面魔法方法重载(Overloading):同门师兄弟的不同绝

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav

Java数组动态扩容的实现示例

《Java数组动态扩容的实现示例》本文主要介绍了Java数组动态扩容的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1 问题2 方法3 结语1 问题实现动态的给数组添加元素效果,实现对数组扩容,原始数组使用静态分配

Java中ArrayList与顺序表示例详解

《Java中ArrayList与顺序表示例详解》顺序表是在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构,:本文主要介绍Java中ArrayList与... 目录前言一、Java集合框架核心接口与分类ArrayList二、顺序表数据结构中的顺序表三、常用代码手动

JAVA项目swing转javafx语法规则以及示例代码

《JAVA项目swing转javafx语法规则以及示例代码》:本文主要介绍JAVA项目swing转javafx语法规则以及示例代码的相关资料,文中详细讲解了主类继承、窗口创建、布局管理、控件替换、... 目录最常用的“一行换一行”速查表(直接全局替换)实际转换示例(JFramejs → JavaFX)迁移建

Spring Boot Interceptor的原理、配置、顺序控制及与Filter的关键区别对比分析

《SpringBootInterceptor的原理、配置、顺序控制及与Filter的关键区别对比分析》本文主要介绍了SpringBoot中的拦截器(Interceptor)及其与过滤器(Filt... 目录前言一、核心功能二、拦截器的实现2.1 定义自定义拦截器2.2 注册拦截器三、多拦截器的执行顺序四、过

JAVA线程的周期及调度机制详解

《JAVA线程的周期及调度机制详解》Java线程的生命周期包括NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING和TERMINATED,线程调度依赖操作系统,采用抢占... 目录Java线程的生命周期线程状态转换示例代码JAVA线程调度机制优先级设置示例注意事项JAVA线程

JavaWeb项目创建、部署、连接数据库保姆级教程(tomcat)

《JavaWeb项目创建、部署、连接数据库保姆级教程(tomcat)》:本文主要介绍如何在IntelliJIDEA2020.1中创建和部署一个JavaWeb项目,包括创建项目、配置Tomcat服务... 目录简介:一、创建项目二、tomcat部署1、将tomcat解压在一个自己找得到路径2、在idea中添加