JAVA发送HTTP请求,并接受返回内容

转自:http://blog.csdn.net/atco/article/details/7949210

参考:http://www.cnblogs.com/nick-huang/p/3859353.html

http://www.oschina.net/code/snippet_582384_44785

http://lavasoft.blog.51cto.com/62575/175911/

http://www.2cto.com/kf/201407/314279.html

http://www.cnblogs.com/xdp-gacl/p/3789624.html

使用OutputStream流输出中文注意问题:

  在服务器端,数据是以哪个码表输出的,那么就要控制客户端浏览器以相应的码表打开,比如:outputStream.write("中国".getBytes("UTF-8"));使用OutputStream流向客户端浏览器输出中文,以UTF-8的编码进行输出,此时就要控制客户端浏览器以UTF-8的编码打开,否则显示的时候就会出现中文乱码,那么在服务器端如何控制客户端浏览器以以UTF-8的编码显示数据呢?可以通过设置响应头控制浏览器的行为,例如:response.setHeader("content-type", "text/html;charset=UTF-8");通过设置响应头控制浏览器以UTF-8的编码显示数据。

使用PrintWriter流输出中文注意问题:

  在获取PrintWriter输出流之前首先使用"response.setCharacterEncoding(charset)"设置字符以什么样的编码输出到浏览器,如:response.setCharacterEncoding("UTF-8");设置将字符以"UTF-8"编码输出到客户端浏览器,然后再使用response.getWriter();获取PrintWriter输出流,这两个步骤不能颠倒,如下:

 response.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器
2 /**
3 * PrintWriter out = response.getWriter();这句代码必须放在response.setCharacterEncoding("UTF-8");之后
4 * 否则response.setCharacterEncoding("UTF-8")这行代码的设置将无效,浏览器显示的时候还是乱码
5 */
6 PrintWriter out = response.getWriter();//获取PrintWriter输出流

在编写下载文件功能时,要使用OutputStream流,避免使用PrintWriter流,因为OutputStream流是字节流,可以处理任意类型的数据,而PrintWriter流是字符流,只能处理字符数据,如果用字符流处理字节数据,会导致数据丢失。


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

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

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

最后,让我们写一个应用类,测试以上代码是否正确 
[java]  view plain  copy
  1. package atco.http;  
  2.   
  3. public class Test {  
  4.   
  5.     /** 
  6.      * @Description: TODO 
  7.      * @param @param args     
  8.      * @return      
  9.      * @throws  
  10.      */  
  11.     public static void main(String[] args) {  
  12.         // TODO Auto-generated method stub  
  13.         try {       
  14.             HttpRequester request = new HttpRequester();  
  15.             request.setDefaultContentEncoding("utf-8");  
  16.             HttpRespons hr = request.sendGet("http://www.csdn.net");       
  17.         
  18.             System.out.println(hr.getUrlString());       
  19.             System.out.println(hr.getProtocol());       
  20.             System.out.println(hr.getHost());       
  21.             System.out.println(hr.getPort());       
  22.             System.out.println(hr.getContentEncoding());       
  23.             System.out.println(hr.getMethod());       
  24.                    
  25.             System.out.println(hr.getContent());       
  26.         
  27.         } catch (Exception e) {       
  28.             e.printStackTrace();       
  29.         }   
  30.     }  
  31.   
  32. }  
Java发送HTTP请求并获取返回数据可以使用Java的内置类库java.net和java.io。 以下是一个示例代码,使用Java的URL类发送HTTP GET请求并获取返回的数据: ```java import java.net.*; import java.io.*; public class HttpTest { public static void main(String[] args) { try { // 创建一个URL对象 URL url = new URL("http://example.com"); // 打开一个连接到URL的连接 HttpURLConnection con = (HttpURLConnection) url.openConnection(); // 设置请求方法为GET con.setRequestMethod("GET"); // 获取响应状态码 int status = con.getResponseCode(); // 如果响应状态码为200表示请求成功 if (status == 200) { // 获取输入流并读取返回的数据 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer content = new StringBuffer(); while ((inputLine = in.readLine()) != null) { content.append(inputLine); } in.close(); // 输出返回数据 System.out.println(content.toString()); } else { System.out.println("请求失败"); } } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们使用了java.net中的URL类和HttpURLConnection类。我们首先创建一个URL对象,然后通过openConnection()方法打开一个连接到URL的连接。我们可以设置请求方法和请求头,发送请求并获取响应状态码。如果响应状态码为200,表示请求成功,我们可以获取输入流并读取返回的数据。最后,我们将返回的数据输出到控制台。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值