码迷,mamicode.com
首页 > Web开发 > 详细

关于HTTP请求的那些事

时间:2016-07-13 17:34:35      阅读:651      评论:0      收藏:0      [点我收藏+]

标签:

最近项目做接口服务中用到了两种请求方式,一种是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. 释放连接。无论执行方法是否成功,都必须释放连接

    package com.test;  
      
    import java.io.File;  
    import java.io.FileInputStream;  
    import java.io.IOException;  
    import java.io.UnsupportedEncodingException;  
    import java.security.KeyManagementException;  
    import java.security.KeyStore;  
    import java.security.KeyStoreException;  
    import java.security.NoSuchAlgorithmException;  
    import java.security.cert.CertificateException;  
    import java.util.ArrayList;  
    import java.util.List;  
      
    import javax.net.ssl.SSLContext;  
      
    import org.apache.http.HttpEntity;  
    import org.apache.http.NameValuePair;  
    import org.apache.http.ParseException;  
    import org.apache.http.client.ClientProtocolException;  
    import org.apache.http.client.entity.UrlEncodedFormEntity;  
    import org.apache.http.client.methods.CloseableHttpResponse;  
    import org.apache.http.client.methods.HttpGet;  
    import org.apache.http.client.methods.HttpPost;  
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
    import org.apache.http.conn.ssl.SSLContexts;  
    import org.apache.http.conn.ssl.TrustSelfSignedStrategy;  
    import org.apache.http.entity.ContentType;  
    import org.apache.http.entity.mime.MultipartEntityBuilder;  
    import org.apache.http.entity.mime.content.FileBody;  
    import org.apache.http.entity.mime.content.StringBody;  
    import org.apache.http.impl.client.CloseableHttpClient;  
    import org.apache.http.impl.client.HttpClients;  
    import org.apache.http.message.BasicNameValuePair;  
    import org.apache.http.util.EntityUtils;  
    import org.junit.Test;  
      
    public class HttpClientTest {  
      
        @Test  
        public void jUnitTest() {  
            get();  
        }  
      
        /** 
         * HttpClient连接SSL 
         */  
        public void ssl() {  
            CloseableHttpClient httpclient = null;  
            try {  
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
                FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));  
                try {  
                    // 加载keyStore d:\\tomcat.keystore    
                    trustStore.load(instream, "123456".toCharArray());  
                } catch (CertificateException e) {  
                    e.printStackTrace();  
                } finally {  
                    try {  
                        instream.close();  
                    } catch (Exception ignore) {  
                    }  
                }  
                // 相信自己的CA和所有自签名的证书  
                SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();  
                // 只允许使用TLSv1协议  
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,  
                        SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);  
                httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();  
                // 创建http请求(get方式)  
                HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");  
                System.out.println("executing request" + httpget.getRequestLine());  
                CloseableHttpResponse response = httpclient.execute(httpget);  
                try {  
                    HttpEntity entity = response.getEntity();  
                    System.out.println("----------------------------------------");  
                    System.out.println(response.getStatusLine());  
                    if (entity != null) {  
                        System.out.println("Response content length: " + entity.getContentLength());  
                        System.out.println(EntityUtils.toString(entity));  
                        EntityUtils.consume(entity);  
                    }  
                } finally {  
                    response.close();  
                }  
            } catch (ParseException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            } catch (KeyManagementException e) {  
                e.printStackTrace();  
            } catch (NoSuchAlgorithmException e) {  
                e.printStackTrace();  
            } catch (KeyStoreException e) {  
                e.printStackTrace();  
            } finally {  
                if (httpclient != null) {  
                    try {  
                        httpclient.close();  
                    } catch (IOException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
      
        /** 
         * post方式提交表单(模拟用户登录请求) 
         */  
        public void postForm() {  
            // 创建默认的httpClient实例.    
            CloseableHttpClient httpclient = HttpClients.createDefault();  
            // 创建httppost    
            HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");  
            // 创建参数队列    
            List<namevaluepair> formparams = new ArrayList<namevaluepair>();  
            formparams.add(new BasicNameValuePair("username", "admin"));  
            formparams.add(new BasicNameValuePair("password", "123456"));  
            UrlEncodedFormEntity uefEntity;  
            try {  
                uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
                httppost.setEntity(uefEntity);  
                System.out.println("executing request " + httppost.getURI());  
                CloseableHttpResponse response = httpclient.execute(httppost);  
                try {  
                    HttpEntity entity = response.getEntity();  
                    if (entity != null) {  
                        System.out.println("--------------------------------------");  
                        System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));  
                        System.out.println("--------------------------------------");  
                    }  
                } finally {  
                    response.close();  
                }  
            } catch (ClientProtocolException e) {  
                e.printStackTrace();  
            } catch (UnsupportedEncodingException e1) {  
                e1.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally {  
                // 关闭连接,释放资源    
                try {  
                    httpclient.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
      
        /** 
         * 发送 post请求访问本地应用并根据传递参数不同返回不同结果 
         */  
        public void post() {  
            // 创建默认的httpClient实例.    
            CloseableHttpClient httpclient = HttpClients.createDefault();  
            // 创建httppost    
            HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");  
            // 创建参数队列    
            List<namevaluepair> formparams = new ArrayList<namevaluepair>();  
            formparams.add(new BasicNameValuePair("type", "house"));  
            UrlEncodedFormEntity uefEntity;  
            try {  
                uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
                httppost.setEntity(uefEntity);  
                System.out.println("executing request " + httppost.getURI());  
                CloseableHttpResponse response = httpclient.execute(httppost);  
                try {  
                    HttpEntity entity = response.getEntity();  
                    if (entity != null) {  
                        System.out.println("--------------------------------------");  
                        System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));  
                        System.out.println("--------------------------------------");  
                    }  
                } finally {  
                    response.close();  
                }  
            } catch (ClientProtocolException e) {  
                e.printStackTrace();  
            } catch (UnsupportedEncodingException e1) {  
                e1.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally {  
                // 关闭连接,释放资源    
                try {  
                    httpclient.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
      
        /** 
         * 发送 get请求 
         */  
        public void get() {  
            CloseableHttpClient httpclient = HttpClients.createDefault();  
            try {  
                // 创建httpget.    
                HttpGet httpget = new HttpGet("http://www.baidu.com/");  
                System.out.println("executing request " + httpget.getURI());  
                // 执行get请求.    
                CloseableHttpResponse response = httpclient.execute(httpget);  
                try {  
                    // 获取响应实体    
                    HttpEntity entity = response.getEntity();  
                    System.out.println("--------------------------------------");  
                    // 打印响应状态    
                    System.out.println(response.getStatusLine());  
                    if (entity != null) {  
                        // 打印响应内容长度    
                        System.out.println("Response content length: " + entity.getContentLength());  
                        // 打印响应内容    
                        System.out.println("Response content: " + EntityUtils.toString(entity));  
                    }  
                    System.out.println("------------------------------------");  
                } finally {  
                    response.close();  
                }  
            } catch (ClientProtocolException e) {  
                e.printStackTrace();  
            } catch (ParseException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally {  
                // 关闭连接,释放资源    
                try {  
                    httpclient.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
      
        /** 
         * 上传文件 
         */  
        public void upload() {  
            CloseableHttpClient httpclient = HttpClients.createDefault();  
            try {  
                HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");  
      
                FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));  
                StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);  
      
                HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();  
      
                httppost.setEntity(reqEntity);  
      
                System.out.println("executing request " + httppost.getRequestLine());  
                CloseableHttpResponse response = httpclient.execute(httppost);  
                try {  
                    System.out.println("----------------------------------------");  
                    System.out.println(response.getStatusLine());  
                    HttpEntity resEntity = response.getEntity();  
                    if (resEntity != null) {  
                        System.out.println("Response content length: " + resEntity.getContentLength());  
                    }  
                    EntityUtils.consume(resEntity);  
                } finally {  
                    response.close();  
                }  
            } catch (ClientProtocolException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally {  
                try {  
                    httpclient.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }

(2)使用JDK自带特性

package net.parse.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

public class HttpTools {
	/**
	 * 返回响应头信息
	 * @param url
	 * @return
	 */
	public static String GetHttpHeader(String url,String referer){
			String result = "";
			try {
				URL u = new URL(url);
				HttpURLConnection conn = (HttpURLConnection)u.openConnection();
				conn.setRequestMethod("GET"); 
				conn.addRequestProperty("Referer", referer);
				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");
				//必须设置false,否则会自动redirect到重定向后的地址 
	            conn.setInstanceFollowRedirects(false);
	            conn.connect();
	            if (conn.getResponseCode() == 302 || conn.getResponseCode() == 301) { 
	                //如果会重定向,保存302重定向地址,以及Cookies,然后重新发送请求(模拟请求)
	                result = conn.getHeaderField("Location"); 
	            //    Map<String, List<String>> map = conn.getHeaderFields();
	        //        for (String key : map.keySet()) {
	        //        	System.out.println(key+"    ----->"+ map.get(key));
	        //        }
	        //        GetHttpHeader(result,"");
	            }
	            
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
	}
	
	/**
	 * 获取网站返回内容
	 * @param url
	 * @return
	 */
	public static String Getcode(String url,String encode,String referer){
		if(encode==""){encode="UTF-8";}
		String result = "";
		String temp="";
		try {
			URL u = new URL(url);
			HttpURLConnection conn = (HttpURLConnection)u.openConnection();
			conn.setRequestProperty("Referer", referer);
			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");
            InputStreamReader isr = new InputStreamReader(conn.getInputStream(),encode);
            BufferedReader br = new BufferedReader(isr);  
            while((temp = br.readLine()) != null){  
			result +=temp+"\n";
			}
           if (isr!=null) {
        	   isr.close();
           }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	 /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param,String referer,String Cookies) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Accept", "*/*");
//            conn.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            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");
            conn.setRequestProperty("Cookie", Cookies);
            conn.setRequestProperty("Referer", referer);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line+"\n";
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    
	
}

package net.parse.tool;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;




public class HttpsTools {
	/**
	 * 获取网站返回内容
	 * @param url
	 * @return
	 */
	public static String Getcode(String requsturl,String requestMethod,String encode,String referer,String outputStr){
        StringBuffer buffer = new StringBuffer();
        if (null==requestMethod) {
        	requestMethod="GET";
		}
        if(encode==null){
        	encode="UTF-8";
        }
		 try {  
	            // 创建SSLContext对象,并使用我们指定的信任管理器初始化  
	            TrustManager[] tm = { new MyX509TrustManager() };  
	            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
	            sslContext.init(null, tm, new java.security.SecureRandom());  
	            // 从上述SSLContext对象中得到SSLSocketFactory对象  
	            SSLSocketFactory ssf = sslContext.getSocketFactory();  
	  
	            URL url = new URL(requsturl);  
	            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
	            httpUrlConn.setSSLSocketFactory(ssf);  
	            httpUrlConn.setRequestProperty("referer", referer);
	            httpUrlConn.setDoOutput(true);  
	            httpUrlConn.setDoInput(true);  
	            httpUrlConn.setUseCaches(false);  
	            // 设置请求方式(GET/POST)  
	            httpUrlConn.setRequestMethod(requestMethod);  
	  
	            if ("GET".equalsIgnoreCase(requestMethod))  
	                httpUrlConn.connect();  
	  
	            // 当有数据需要提交时  
	            if (null != outputStr) {  
	                OutputStream outputStream = httpUrlConn.getOutputStream();  
	                // 注意编码格式,防止中文乱码  
	                outputStream.write(outputStr.getBytes(encode));  
	                outputStream.close();  
	            }  
	  
	            // 将返回的输入流转换成字符串  
	            InputStream inputStream = httpUrlConn.getInputStream();  
	            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, encode);  
	            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
	  
	            String str = null;  
	            while ((str = bufferedReader.readLine()) != null) {  
	                buffer.append(str+"\n");  
	            }  
	            bufferedReader.close();  
	            inputStreamReader.close();  
	            // 释放资源  
	            inputStream.close();  
	            inputStream = null;  
	            httpUrlConn.disconnect();  
	  
	        } catch (Exception e) {  
	            e.printStackTrace();
	        }  
	        return buffer.toString();  
  
	}
	
}







关于HTTP请求的那些事

标签:

原文地址:http://blog.csdn.net/tanyunlong_nice/article/details/51863012

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!