java http请求

  1. package com.bijian.study;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.DataOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStreamReader;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.URL;  
  9. import java.net.URLEncoder;  
  10.   
  11. public class PostRequest {  
  12.   
  13.     public static final String GET_URL = "http://localhost:8080/SpringMVC/greeting";  
  14.   
  15.     public static final String POST_URL = "http://localhost:8080/SpringMVC/greeting";  
  16.       
  17.     public static void readContentFromGet() throws IOException {  
  18.           
  19.         // 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码  
  20.         String getURL = GET_URL + "?name=" + URLEncoder.encode("zhangshan""utf-8");  
  21.         URL getUrl = new URL(getURL);  
  22.         // 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,  
  23.         // 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection  
  24.         HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();  
  25.         // 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到服务器  
  26.         connection.connect();  
  27.         // 取得输入流,并使用Reader读取  
  28.         BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编码,否则中文乱码  
  29.         System.out.println("=============================");  
  30.         System.out.println("Contents of get request");  
  31.         System.out.println("=============================");  
  32.         String lines;  
  33.         while ((lines = reader.readLine()) != null) {  
  34.             // lines = new String(lines.getBytes(), "utf-8");  
  35.             System.out.println(lines);  
  36.         }  
  37.         reader.close();  
  38.         // 断开连接  
  39.         connection.disconnect();  
  40.         System.out.println("=============================");  
  41.         System.out.println("Contents of get request ends");  
  42.         System.out.println("=============================");  
  43.     }  
  44.   
  45.     public static void readContentFromPost() throws IOException {  
  46.           
  47.         // Post请求的url,与get不同的是不需要带参数  
  48.         URL postUrl = new URL(POST_URL);  
  49.         // 打开连接  
  50.         HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();  
  51.         // Output to the connection. Default is false, set to true because post method must write something to the connection  
  52.         // 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true  
  53.         connection.setDoOutput(true);  
  54.         // Read from the connection. Default is true.  
  55.         connection.setDoInput(true);  
  56.         // Set the post method. Default is GET  
  57.         connection.setRequestMethod("POST");  
  58.         // Post cannot use caches  
  59.         // Post 请求不能使用缓存  
  60.         connection.setUseCaches(false);  
  61.           
  62.         // This method takes effects to every instances of this class.URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。  
  63.         // connection.setFollowRedirects(true);  
  64.   
  65.         // This methods only takes effacts to this instance.URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数  
  66.         connection.setInstanceFollowRedirects(true);  
  67.         // Set the content type to urlencoded,because we will write some URL-encoded content to the connection. Settings above must be set before connect!  
  68.         // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode进行编码  
  69.         connection.setRequestProperty("Content-Type""application/x-www-form-urlencoded");  
  70.         // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,  
  71.         // 要注意的是connection.getOutputStream会隐含的进行connect。  
  72.         connection.connect();  
  73.         DataOutputStream out = new DataOutputStream(connection.getOutputStream());  
  74.         // The URL-encoded contend  
  75.         // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致  
  76.         String content = "name=" + URLEncoder.encode("张三""utf-8");  
  77.         // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面  
  78.         out.writeBytes(content);  
  79.         out.flush();  
  80.         out.close();// flush and close  
  81.         BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编码,否则中文乱码  
  82.         String line = "";  
  83.         System.out.println("=============================");  
  84.         System.out.println("Contents of post request");  
  85.         System.out.println("=============================");  
  86.         while ((line = reader.readLine()) != null) {  
  87.             // line = new String(line.getBytes(), "utf-8");  
  88.             System.out.println(line);  
  89.         }  
  90.         System.out.println("=============================");  
  91.         System.out.println("Contents of post request ends");  
  92.         System.out.println("=============================");  
  93.         reader.close();  
  94.         connection.disconnect();  
  95.     }  
  96.       
  97.     public static void main(String[] args) {  
  98.           
  99.         try {  
  100.             readContentFromGet();  
  101.             readContentFromPost();  
  102.         } catch (IOException e) {  
  103.             e.printStackTrace();  
  104.         }  
  105.     }  
  106. }  

运行结果:

Text代码   收藏代码
  1. =============================  
  2. Contents of get request  
  3. =============================  
  4.   
  5.     
  6. <!DOCTYPE html>     
  7. <html>     
  8. <head>     
  9.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">     
  10.     <title>Hello</title>     
  11. </head>     
  12. <body>     
  13.     你好,zhangshan  
  14. </body>     
  15. </html>  
  16. =============================  
  17. Contents of get request ends  
  18. =============================  
  19. =============================  
  20. Contents of post request  
  21. =============================  
  22.   
  23.     
  24. <!DOCTYPE html>     
  25. <html>     
  26. <head>     
  27.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">     
  28.     <title>Hello</title>     
  29. </head>     
  30. <body>     
  31.     你好,张三  
  32. </body>     
  33. </html>  
  34. =============================  
  35. Contents of post request ends  
  36. =============================  

        注意:通过BufferedReader 读取远程返回的数据时,必须设置读取编码,否则中文会乱码! 

 

        HttpURLConnection.connect函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。无论是post还是get,http请求实际上直到HttpURLConnection.getInputStream()这个函数里面才正式发送出去。

        在readContentFromPost() 中,顺序是重中之重,对connection对象的一切配置(那一堆set函数)都必须要在connect()函数执行之前完成。而对 outputStream的写操作,又必须要在inputStream的读操作之前。这些顺序实际上是由http请求的格式决定的。

        http 请求实际上由两部分组成,一个是http头,所有关于此次http请求的配置都在http头里面定义,一个是正文content,在connect()函数里面,会根据HttpURLConnection对象的配置值生成http头,因此在调用connect函数之前,就必须把所有的配置准备好。

        紧接着http头的是http请求的正文,正文的内容通过outputStream写入,实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,而是在流关闭后,根据输入的内容生成http正文。

        至此,http请求的东西已经准备就绪。在getInputStream()函数调用的时候,就会把准备好的http请求正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。由于http请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在getInputStream()函数之后对connection对象进行设置(对http头的信息进行修改)或者写入 outputStream(对正文进行修改)都是没有意义的了,执行这些操作会导致异常的发生。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值