关于HTTP请求

来源:互联网 发布:手机淘宝店铺管理软件 编辑:程序博客网 时间:2024/06/06 16:41

最近项目做接口服务中用到了两种请求方式,一种是webservice,另一种是HttpPost

就Http请求方式详细的学习和了解了下

一、TCP/IP

1. 协议
a. TCP/IP整体构架概述
TCP/IP协议并不完全符合OSI的七层参考模型。传统的开放式系统互连参考模型,是一种通信协议的7层抽象的参考模型,其中每一层执行某一特定任务。该模型的目的是使各种硬件在相同的层次上相互通信。这7层是:物理层、数据链路层、网路层、传输层、话路层、表示层和应用层。而TCP/IP通讯协议采用了4层的层级结构,每一层都呼叫它的下一层所提供的网络来完成自己的需求。这4层分别为:
i. 应用层:应用程序间沟通的层,如超文本传送协议(HTTP)、简单电子邮件传输(SMTP)、文件传输协议(FTP)、网络远程访问协议(Telnet)等。
ii. 传输层:在此层中,它提供了节点间的数据传送服务,如传输控制协议(TCP)、用户数据报协议(UDP)等,TCP和UDP给数据包加入传输数据并把它传输到下一层中,这一层负责传送数据,并且确定数据已被送达并接收。

iii. 互连网络层:负责提供基本的数据封包传送功能,让每一块数据包都能够到达目的主机(但不检查是否被正确接收),如网际协议(IP)。
iv. 网络接口层:对实际的网络媒体的管理,定义如何使用实际网络(如Ethernet、Serial Line等)来传送数据。
b. HTTP协议介绍:
i. HTTP是一种超文本传送协议(HyperText Transfer Protocol),是一套计算机在网络中通信的一种规则。在TCP/IP体系结构中,HTTP属于应用层协议,位于TCP/IP协议的顶层
ii. HTTP是一种无状态的的协议,意思是指 在Web 浏览器(客户端)和 Web 服务器之间不需要建立持久的连接。整个过程就是当一个客户端向服务器端发送一个请求(request),然后Web服务器返回一个响应 (response),之后连接就关闭了,在服务端此时是没有保留连接的信息。
iii. HTTP 遵循 请求/响应(request/response) 模型的,所有的通信交互都被构造在一套请求和响应模型中。
iv. 浏览WEB时,浏览器通过HTTP协议与WEB服务器交换信息,Web服务器向Web浏览器返回的文件都有与之相关的类型,这些信息类型的格式由MIME定义。
c. 协议的java实现方式

不论是TCP/IP协议也好,还是HTTP协议也好,java都是通过套接字(java.net.Socket)来实现的,可以参考我的另一篇技术博客:一个项目看java TCP/IP Socket编程(1.3版)
2. HTTP报文接口及客户端和服务器端交互原理
a. HTTP定义的事务处理由以下四步组成:
i. 建立连接:
例如我在浏览器里输入 http://cuishen.iteye.com,客户端请求这个地址时即打开了web服务器HTTP端口的一个套接字。因为在网络中间作为传递数据的实体介质就是网线,数据实质上是通过IO流进行输出和输入,这就不难理解我们为什么在写一个Servlet的时候要引用 import java.io.*; 的原因 ,包括我们在向客户端回发结果的时候要用到PrintWriter对象的println()方法。其实请求的这个地址还要加上端口号80,80可以不写,是因为浏览器默认的端口号是80。
在Java底层代码中是这样实现的,只不过它们已经帮我们做了。
1.          Socket socket = new Socket("cuishen.iteye.com",80);    
2.          InputStream in = socket.getInputStream();    
3.          OutputStream out = socket.getOutputStream();   
ii. 客户端发送HTTP请求报文(request)
一旦建立了TCP连接,Web浏览器就会向Web服务器发送请求命令,是一个ASCII文本请求行,后跟0个或多个HTTP头标,一个空行和实现请求的任意数据。
即报文分四个部分:请求行,请求头标,空行和请求数据
1)请求行

请求行由三个标记组成:请求方法、请求URL和HTTP版本,中间用空格分开
例如: GET cuishen.iteye.com/blog/242842 HTTP/1.1
HTTP规范定义了8种可能的请求方法:(最常见的就是 GET 和 POST 两种方法)
  • GET -- 检索URI中标识资源的一个简单请求
  • HEAD -- 与GET方法相同,服务器只返回状态行和头标,并不返回请求文档
  • POST -- 服务器接受被写入客户端输出流中的数据的请求
  • PUT -- 服务器保存请求数据作为指定URI新内容的请求
  • DELETE -- 服务器删除URI中命名的资源的请求
  • OPTIONS -- 关于服务器支持的请求方法信息的请求
  • TRACE -- Web服务器反馈Http请求和其头标的请求
  • CONNECT -- 已文档化但当前未实现的一个方法,预留做隧道处理
2)请求头标
请求头标:由key :value 健值组成,每行一对。请求头标用来通知服务器有关客户端的功能和标识。
HOST -- 请求的哪一个服务器端地址,主地址,比如:我的技术blog:cuishen.iteye.com
User-Agent -- 用户即客户端可以使用的浏览器 ,如: Mozilla/4.0
Accept -- 即客户端可以接受的MIME 类型列表,如image/gif、text/html、application/msword
Content-Length -- 只适用于POST请求,以字节给出POST数据的尺寸
3)空行
发送回车符和退行,通知服务器以下不再有头标。
4)请求数据
使用POST传送数据,最常使用的是Content-Type和Content-Length头标。
请求报文总结:

我们可以这样写出一个标准的 HTTP请求:
POST /blog/242842 HTTP1.1
HOST: cuishen.iteye.com/
User-Agent: Mozilla/4.0
Accpt: image/gif,text/html,application/pdf,image/png...
key=value&key=value&key=value...... (POST()请求的数据)
这上面的一个例子意思是:
我要去访问的服务器端的地址是cuishen.iteye.com/ 它下面的资源 /blog/242842
连起来就是: cuishen.iteye.com/blog/242842
这个页面用的是 HTTP1.1 规范,我的浏览器版本是Mozilla/4.0 
可以支持的MIME格式为 image/gif,text/html,application/pdf,image/png...等等
 
这个MIME格式我们在servlet中写法是:response.setContentType("text/html;charset=gb2312");
或者在jsp中写法是:<%@ page contentType="text/html;charset=gb2312"%>
或者在html中写法是:<meta http-equiv="content-Type" content="text/html; charset=gb2312">
GET 和 POST 最直观的区别就是:GET方法将数据的请求跟在了所请求的URL后面,也就是在请求行里面我们是这么样来做的:
1.          GET /blog/242842?key=value&key=value&key=value......HTTP1.1 
实际上用 GET 是这样传递数据的:
1.          http://cuishen.iteye.com/?page=2...... 
iii.服务器端响应请求生成结果并回发(response)
Web 服务器解析请求,定位指定的资源 http://cuishen.iteye.com/blog/242842
1)根据请求时的 GET/POST 对应的用servlet里的 doGet() / doPost()方法来处理(有可能是一些业务逻辑,也有可能是一些验证等等,也有可能是一些数据查询,提交等等)其有效的数据就来源于key=value&key=value&key=value......,以及其它的一些封装在 request 对象中的数据资源。
2)处理请求之后,由 response 对象得到 java.io.PrintWriter 输出流对象out,通过 out.println(); 将数据以指定的格式,如按照response.setcontentType("text/html;charset=gb2312");的格式输出到输出流。
它的响应报文与请求报文非常类似,其区别就在于:我们在请求阶段的请求行被状态行给替换了,再来看响应报文:
3)一个响应报文由四个部分组成:状态行、响应头标、空行、响应数据:
(a).状态行:
状态行由三个标记组成:HTTP版本、响应代码和响应描述。
HTTP1.1 --- 100 --- continue //继续追加后继内容
HTTP1.1 --- 200 --- OK //一切正常
HTTP1.1 --- 301 --- Moved Permanently //请求的文档在其它地方,会自动连接
HTTP1.1 --- 403 --- Forbidden //绝对拒绝你访问这个资源,不管授权没有
HTTP1.1 --- 400 --- Bad Request //客户端请求中的不良语法
HTTP1.1 --- 404 --- Not Found //最常见,绝对是大名鼎鼎的找不到
HTTP响应码:
1xx:提示性信息,告诉客户端应该对某些其它的动作作出响应
2xx:这些就代表了请求成功
3xx:重定向,为了完成请求,必须进一步执行的动作
4xx:客户端错误
500-599: 服务器端的错误
(b).响应头标:像请求头标一样,它们指出服务器的功能,标识出响应数据的细节。
Date: Sat, 31 Dec 2005 23:59:59 GMT --响应生成的日期和时间
ContentType: 'text/html;charset=gb2312'
Content-Length: 122 --响应中的字节数,只在浏览器使用永久(Keep-alive)HTTP连接时需要。
(c).空行:最后一个响应头标之后是一个空行,发送回车符和退行,表明服务器以下不再有头标。
(d).响应数据:HTML文档和图像等,也就是HTML本身。out.println("<html>......");写到客户端。
1.          <html>    
2.          <head>    
3.          <title>Welcome to cuishen's IT blog</title>    
4.          </head>    
5.          <body>    
6.          <!-- 这里是具体的内容,看到了这里    
7.          相信大家对 HTTP 工作原理及客户端与服务器交互过程已经很清楚了吧    
8.          -->     
9.          </body>    
10.       </html> 
iv. 服务器端关闭连接,客户端解析回发响应报文,恢复页面
1)浏览器先解析状态行,查看请求是否成功的状态代码--HTTP响应码:404 400 200 ....
2)解析每一个响应头标,如:
ContentType: text/html;charset=gb2312 
Content-Length: 122 --- 响应中的字节数,只在浏览器使用永久(Keep-alive)HTTP连接时需要。
3)读取响应数据HTML,根据标签<html></html>中的内容恢复标准的HTML格式页面或者其它。
4)一个HTML 文档可能包含其它的需要被载入的资源,浏览器会识别,并对这些资源再进行额外的请求,这个过程可以是循环的方式一直到所有的数据都按照响应头标中规定的格式恢复到页面中。
5)数据传送完毕,服务器端关闭连接,即无状态协议。
总结:不要被高深的名词和理论吓到,其实HTTP客户端和服务器端的交互原理很简单:即先是浏览器和服务器端建立Socket无状态连接,也就是短连接,然后通过IO流进行报文信息(这个报文是严格遵循HTTP报文接口的)的交互,最后会话结束后就关闭连接。对于这些底层的协议和报文的打包解包交互的实现,其实java和浏览器早都已经封装好了,程序员只要专注于业务逻辑的实现就行啦,这些都不必关心!!
二、JAVA实现HTTP请求的几种方式
(1)使用Httpclient JAR包
HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。
使用Httpclient方法的顺序:

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package com.test;    
  2.     
  3. import java.io.File;    
  4. import java.io.FileInputStream;    
  5. import java.io.IOException;    
  6. import java.io.UnsupportedEncodingException;    
  7. import java.security.KeyManagementException;    
  8. import java.security.KeyStore;    
  9. import java.security.KeyStoreException;    
  10. import java.security.NoSuchAlgorithmException;    
  11. import java.security.cert.CertificateException;    
  12. import java.util.ArrayList;    
  13. import java.util.List;    
  14.     
  15. import javax.net.ssl.SSLContext;    
  16.     
  17. import org.apache.http.HttpEntity;    
  18. import org.apache.http.NameValuePair;    
  19. import org.apache.http.ParseException;    
  20. import org.apache.http.client.ClientProtocolException;    
  21. import org.apache.http.client.entity.UrlEncodedFormEntity;    
  22. import org.apache.http.client.methods.CloseableHttpResponse;    
  23. import org.apache.http.client.methods.HttpGet;    
  24. import org.apache.http.client.methods.HttpPost;    
  25. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;    
  26. import org.apache.http.conn.ssl.SSLContexts;    
  27. import org.apache.http.conn.ssl.TrustSelfSignedStrategy;    
  28. import org.apache.http.entity.ContentType;    
  29. import org.apache.http.entity.mime.MultipartEntityBuilder;    
  30. import org.apache.http.entity.mime.content.FileBody;    
  31. import org.apache.http.entity.mime.content.StringBody;    
  32. import org.apache.http.impl.client.CloseableHttpClient;    
  33. import org.apache.http.impl.client.HttpClients;    
  34. import org.apache.http.message.BasicNameValuePair;    
  35. import org.apache.http.util.EntityUtils;    
  36. import org.junit.Test;    
  37.     
  38. public class HttpClientTest {    
  39.     
  40.     @Test    
  41.     public void jUnitTest() {    
  42.         get();    
  43.     }    
  44.     
  45.     /**  
  46.      * HttpClient连接SSL  
  47.      */    
  48.     public void ssl() {    
  49.         CloseableHttpClient httpclient = null;    
  50.         try {    
  51.             KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());    
  52.             FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));    
  53.             try {    
  54.                 // 加载keyStore d:\\tomcat.keystore      
  55.                 trustStore.load(instream, "123456".toCharArray());    
  56.             } catch (CertificateException e) {    
  57.                 e.printStackTrace();    
  58.             } finally {    
  59.                 try {    
  60.                     instream.close();    
  61.                 } catch (Exception ignore) {    
  62.                 }    
  63.             }    
  64.             // 相信自己的CA和所有自签名的证书    
  65.             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();    
  66.             // 只允许使用TLSv1协议    
  67.             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,    
  68.                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);    
  69.             httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();    
  70.             // 创建http请求(get方式)    
  71.             HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");    
  72.             System.out.println("executing request" + httpget.getRequestLine());    
  73.             CloseableHttpResponse response = httpclient.execute(httpget);    
  74.             try {    
  75.                 HttpEntity entity = response.getEntity();    
  76.                 System.out.println("----------------------------------------");    
  77.                 System.out.println(response.getStatusLine());    
  78.                 if (entity != null) {    
  79.                     System.out.println("Response content length: " + entity.getContentLength());    
  80.                     System.out.println(EntityUtils.toString(entity));    
  81.                     EntityUtils.consume(entity);    
  82.                 }    
  83.             } finally {    
  84.                 response.close();    
  85.             }    
  86.         } catch (ParseException e) {    
  87.             e.printStackTrace();    
  88.         } catch (IOException e) {    
  89.             e.printStackTrace();    
  90.         } catch (KeyManagementException e) {    
  91.             e.printStackTrace();    
  92.         } catch (NoSuchAlgorithmException e) {    
  93.             e.printStackTrace();    
  94.         } catch (KeyStoreException e) {    
  95.             e.printStackTrace();    
  96.         } finally {    
  97.             if (httpclient != null) {    
  98.                 try {    
  99.                     httpclient.close();    
  100.                 } catch (IOException e) {    
  101.                     e.printStackTrace();    
  102.                 }    
  103.             }    
  104.         }    
  105.     }    
  106.     
  107.     /**  
  108.      * post方式提交表单(模拟用户登录请求)  
  109.      */    
  110.     public void postForm() {    
  111.         // 创建默认的httpClient实例.      
  112.         CloseableHttpClient httpclient = HttpClients.createDefault();    
  113.         // 创建httppost      
  114.         HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");    
  115.         // 创建参数队列      
  116.         List<namevaluepair> formparams = new ArrayList<namevaluepair>();    
  117.         formparams.add(new BasicNameValuePair("username""admin"));    
  118.         formparams.add(new BasicNameValuePair("password""123456"));    
  119.         UrlEncodedFormEntity uefEntity;    
  120.         try {    
  121.             uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");    
  122.             httppost.setEntity(uefEntity);    
  123.             System.out.println("executing request " + httppost.getURI());    
  124.             CloseableHttpResponse response = httpclient.execute(httppost);    
  125.             try {    
  126.                 HttpEntity entity = response.getEntity();    
  127.                 if (entity != null) {    
  128.                     System.out.println("--------------------------------------");    
  129.                     System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));    
  130.                     System.out.println("--------------------------------------");    
  131.                 }    
  132.             } finally {    
  133.                 response.close();    
  134.             }    
  135.         } catch (ClientProtocolException e) {    
  136.             e.printStackTrace();    
  137.         } catch (UnsupportedEncodingException e1) {    
  138.             e1.printStackTrace();    
  139.         } catch (IOException e) {    
  140.             e.printStackTrace();    
  141.         } finally {    
  142.             // 关闭连接,释放资源      
  143.             try {    
  144.                 httpclient.close();    
  145.             } catch (IOException e) {    
  146.                 e.printStackTrace();    
  147.             }    
  148.         }    
  149.     }    
  150.     
  151.     /**  
  152.      * 发送 post请求访问本地应用并根据传递参数不同返回不同结果  
  153.      */    
  154.     public void post() {    
  155.         // 创建默认的httpClient实例.      
  156.         CloseableHttpClient httpclient = HttpClients.createDefault();    
  157.         // 创建httppost      
  158.         HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");    
  159.         // 创建参数队列      
  160.         List<namevaluepair> formparams = new ArrayList<namevaluepair>();    
  161.         formparams.add(new BasicNameValuePair("type""house"));    
  162.         UrlEncodedFormEntity uefEntity;    
  163.         try {    
  164.             uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");    
  165.             httppost.setEntity(uefEntity);    
  166.             System.out.println("executing request " + httppost.getURI());    
  167.             CloseableHttpResponse response = httpclient.execute(httppost);    
  168.             try {    
  169.                 HttpEntity entity = response.getEntity();    
  170.                 if (entity != null) {    
  171.                     System.out.println("--------------------------------------");    
  172.                     System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));    
  173.                     System.out.println("--------------------------------------");    
  174.                 }    
  175.             } finally {    
  176.                 response.close();    
  177.             }    
  178.         } catch (ClientProtocolException e) {    
  179.             e.printStackTrace();    
  180.         } catch (UnsupportedEncodingException e1) {    
  181.             e1.printStackTrace();    
  182.         } catch (IOException e) {    
  183.             e.printStackTrace();    
  184.         } finally {    
  185.             // 关闭连接,释放资源      
  186.             try {    
  187.                 httpclient.close();    
  188.             } catch (IOException e) {    
  189.                 e.printStackTrace();    
  190.             }    
  191.         }    
  192.     }    
  193.     
  194.     /**  
  195.      * 发送 get请求  
  196.      */    
  197.     public void get() {    
  198.         CloseableHttpClient httpclient = HttpClients.createDefault();    
  199.         try {    
  200.             // 创建httpget.      
  201.             HttpGet httpget = new HttpGet("http://www.baidu.com/");    
  202.             System.out.println("executing request " + httpget.getURI());    
  203.             // 执行get请求.      
  204.             CloseableHttpResponse response = httpclient.execute(httpget);    
  205.             try {    
  206.                 // 获取响应实体      
  207.                 HttpEntity entity = response.getEntity();    
  208.                 System.out.println("--------------------------------------");    
  209.                 // 打印响应状态      
  210.                 System.out.println(response.getStatusLine());    
  211.                 if (entity != null) {    
  212.                     // 打印响应内容长度      
  213.                     System.out.println("Response content length: " + entity.getContentLength());    
  214.                     // 打印响应内容      
  215.                     System.out.println("Response content: " + EntityUtils.toString(entity));    
  216.                 }    
  217.                 System.out.println("------------------------------------");    
  218.             } finally {    
  219.                 response.close();    
  220.             }    
  221.         } catch (ClientProtocolException e) {    
  222.             e.printStackTrace();    
  223.         } catch (ParseException e) {    
  224.             e.printStackTrace();    
  225.         } catch (IOException e) {    
  226.             e.printStackTrace();    
  227.         } finally {    
  228.             // 关闭连接,释放资源      
  229.             try {    
  230.                 httpclient.close();    
  231.             } catch (IOException e) {    
  232.                 e.printStackTrace();    
  233.             }    
  234.         }    
  235.     }    
  236.     
  237.     /**  
  238.      * 上传文件  
  239.      */    
  240.     public void upload() {    
  241.         CloseableHttpClient httpclient = HttpClients.createDefault();    
  242.         try {    
  243.             HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");    
  244.     
  245.             FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));    
  246.             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);    
  247.     
  248.             HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();    
  249.     
  250.             httppost.setEntity(reqEntity);    
  251.     
  252.             System.out.println("executing request " + httppost.getRequestLine());    
  253.             CloseableHttpResponse response = httpclient.execute(httppost);    
  254.             try {    
  255.                 System.out.println("----------------------------------------");    
  256.                 System.out.println(response.getStatusLine());    
  257.                 HttpEntity resEntity = response.getEntity();    
  258.                 if (resEntity != null) {    
  259.                     System.out.println("Response content length: " + resEntity.getContentLength());    
  260.                 }    
  261.                 EntityUtils.consume(resEntity);    
  262.             } finally {    
  263.                 response.close();    
  264.             }    
  265.         } catch (ClientProtocolException e) {    
  266.             e.printStackTrace();    
  267.         } catch (IOException e) {    
  268.             e.printStackTrace();    
  269.         } finally {    
  270.             try {    
  271.                 httpclient.close();    
  272.             } catch (IOException e) {    
  273.                 e.printStackTrace();    
  274.             }    
  275.         }    
  276.     }    
  277. }  

(2)使用JDK自带特性

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package net.parse.tool;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.io.PrintWriter;  
  7. import java.net.CookieManager;  
  8. import java.net.CookieStore;  
  9. import java.net.HttpCookie;  
  10. import java.net.HttpURLConnection;  
  11. import java.net.URL;  
  12. import java.net.URLConnection;  
  13. import java.net.URLDecoder;  
  14. import java.util.List;  
  15. import java.util.Map;  
  16.   
  17. public class HttpTools {  
  18.     /** 
  19.      * 返回响应头信息 
  20.      * @param url 
  21.      * @return 
  22.      */  
  23.     public static String GetHttpHeader(String url,String referer){  
  24.             String result = "";  
  25.             try {  
  26.                 URL u = new URL(url);  
  27.                 HttpURLConnection conn = (HttpURLConnection)u.openConnection();  
  28.                 conn.setRequestMethod("GET");   
  29.                 conn.addRequestProperty("Referer", referer);  
  30.                 conn.setRequestProperty("User-Agent""Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4");  
  31.                 //必须设置false,否则会自动redirect到重定向后的地址   
  32.                 conn.setInstanceFollowRedirects(false);  
  33.                 conn.connect();  
  34.                 if (conn.getResponseCode() == 302 || conn.getResponseCode() == 301) {   
  35.                     //如果会重定向,保存302重定向地址,以及Cookies,然后重新发送请求(模拟请求)  
  36.                     result = conn.getHeaderField("Location");   
  37.                 //    Map<String, List<String>> map = conn.getHeaderFields();  
  38.             //        for (String key : map.keySet()) {  
  39.             //          System.out.println(key+"    ----->"+ map.get(key));  
  40.             //        }  
  41.             //        GetHttpHeader(result,"");  
  42.                 }  
  43.                   
  44.             } catch (Exception e) {  
  45.                 e.printStackTrace();  
  46.             }  
  47.             return result;  
  48.     }  
  49.       
  50.     /** 
  51.      * 获取网站返回内容 
  52.      * @param url 
  53.      * @return 
  54.      */  
  55.     public static String Getcode(String url,String encode,String referer){  
  56.         if(encode==""){encode="UTF-8";}  
  57.         String result = "";  
  58.         String temp="";  
  59.         try {  
  60.             URL u = new URL(url);  
  61.             HttpURLConnection conn = (HttpURLConnection)u.openConnection();  
  62.             conn.setRequestProperty("Referer", referer);  
  63.             conn.setRequestProperty("User-Agent""Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");  
  64.             InputStreamReader isr = new InputStreamReader(conn.getInputStream(),encode);  
  65.             BufferedReader br = new BufferedReader(isr);    
  66.             while((temp = br.readLine()) != null){    
  67.             result +=temp+"\n";  
  68.             }  
  69.            if (isr!=null) {  
  70.                isr.close();  
  71.            }  
  72.         } catch (Exception e) {  
  73.             e.printStackTrace();  
  74.         }  
  75.         return result;  
  76.     }  
  77.       
  78.      /** 
  79.      * 向指定 URL 发送POST方法的请求 
  80.      *  
  81.      * @param url 
  82.      *            发送请求的 URL 
  83.      * @param param 
  84.      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 
  85.      * @return 所代表远程资源的响应结果 
  86.      */  
  87.     public static String sendPost(String url, String param,String referer,String Cookies) {  
  88.         PrintWriter out = null;  
  89.         BufferedReader in = null;  
  90.         String result = "";  
  91.         try {  
  92.             URL realUrl = new URL(url);  
  93.             // 打开和URL之间的连接  
  94.             URLConnection conn = realUrl.openConnection();  
  95.             // 设置通用的请求属性  
  96.             conn.setRequestProperty("Accept""*/*");  
  97. //            conn.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");  
  98.             conn.setRequestProperty("Connection""Keep-Alive");  
  99.             conn.setRequestProperty("User-Agent","Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36");  
  100.             conn.setRequestProperty("Cookie", Cookies);  
  101.             conn.setRequestProperty("Referer", referer);  
  102.             // 发送POST请求必须设置如下两行  
  103.             conn.setDoOutput(true);  
  104.             conn.setDoInput(true);  
  105.             // 获取URLConnection对象对应的输出流  
  106.             out = new PrintWriter(conn.getOutputStream());  
  107.             // 发送请求参数  
  108.             out.print(param);  
  109.             // flush输出流的缓冲  
  110.             out.flush();  
  111.             // 定义BufferedReader输入流来读取URL的响应  
  112.             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  113.             String line;  
  114.             while ((line = in.readLine()) != null) {  
  115.                 result += line+"\n";  
  116.             }  
  117.         } catch (Exception e) {  
  118.             System.out.println("发送 POST 请求出现异常!"+e);  
  119.             e.printStackTrace();  
  120.         }  
  121.         //使用finally块来关闭输出流、输入流  
  122.         finally{  
  123.             try{  
  124.                 if(out!=null){  
  125.                     out.close();  
  126.                 }  
  127.                 if(in!=null){  
  128.                     in.close();  
  129.                 }  
  130.             }  
  131.             catch(IOException ex){  
  132.                 ex.printStackTrace();  
  133.             }  
  134.         }  
  135.         return result;  
  136.     }      
  137.       
  138. }  

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package net.parse.tool;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.io.OutputStream;  
  7. import java.net.URL;  
  8.   
  9. import javax.net.ssl.HttpsURLConnection;  
  10. import javax.net.ssl.SSLContext;  
  11. import javax.net.ssl.SSLSocketFactory;  
  12. import javax.net.ssl.TrustManager;  
  13.   
  14.   
  15.   
  16.   
  17. public class HttpsTools {  
  18.     /** 
  19.      * 获取网站返回内容 
  20.      * @param url 
  21.      * @return 
  22.      */  
  23.     public static String Getcode(String requsturl,String requestMethod,String encode,String referer,String outputStr){  
  24.         StringBuffer buffer = new StringBuffer();  
  25.         if (null==requestMethod) {  
  26.             requestMethod="GET";  
  27.         }  
  28.         if(encode==null){  
  29.             encode="UTF-8";  
  30.         }  
  31.          try {    
  32.                 // 创建SSLContext对象,并使用我们指定的信任管理器初始化    
  33.                 TrustManager[] tm = { new MyX509TrustManager() };    
  34.                 SSLContext sslContext = SSLContext.getInstance("SSL""SunJSSE");    
  35.                 sslContext.init(null, tm, new java.security.SecureRandom());    
  36.                 // 从上述SSLContext对象中得到SSLSocketFactory对象    
  37.                 SSLSocketFactory ssf = sslContext.getSocketFactory();    
  38.         
  39.                 URL url = new URL(requsturl);    
  40.                 HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();    
  41.                 httpUrlConn.setSSLSocketFactory(ssf);    
  42.                 httpUrlConn.setRequestProperty("referer", referer);  
  43.                 httpUrlConn.setDoOutput(true);    
  44.                 httpUrlConn.setDoInput(true);    
  45.                 httpUrlConn.setUseCaches(false);    
  46.                 // 设置请求方式(GET/POST)    
  47.                 httpUrlConn.setRequestMethod(requestMethod);    
  48.         
  49.                 if ("GET".equalsIgnoreCase(requestMethod))    
  50.                     httpUrlConn.connect();    
  51.         
  52.                 // 当有数据需要提交时    
  53.                 if (null != outputStr) {    
  54.                     OutputStream outputStream = httpUrlConn.getOutputStream();    
  55.                     // 注意编码格式,防止中文乱码    
  56.                     outputStream.write(outputStr.getBytes(encode));    
  57.                     outputStream.close();    
  58.                 }    
  59.         
  60.                 // 将返回的输入流转换成字符串    
  61.                 InputStream inputStream = httpUrlConn.getInputStream();    
  62.                 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, encode);    
  63.                 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);    
  64.         
  65.                 String str = null;    
  66.                 while ((str = bufferedReader.readLine()) != null) {    
  67.                     buffer.append(str+"\n");    
  68.                 }    
  69.                 bufferedReader.close();    
  70.                 inputStreamReader.close();    
  71.                 // 释放资源    
  72.                 inputStream.close();    
  73.                 inputStream = null;    
  74.                 httpUrlConn.disconnect();    
  75.         
  76.             } catch (Exception e) {    
  77.                 e.printStackTrace();  
  78.             }    
  79.             return buffer.toString();    
  80.     
  81.     }  
  82.       
  83. }  
转载地址:http://blog.csdn.net/tanyunlong_nice/article/details/51863012

1 0
原创粉丝点击