httpClient教程.docx

上传人:b****5 文档编号:8019783 上传时间:2023-01-28 格式:DOCX 页数:22 大小:22.79KB
下载 相关 举报
httpClient教程.docx_第1页
第1页 / 共22页
httpClient教程.docx_第2页
第2页 / 共22页
httpClient教程.docx_第3页
第3页 / 共22页
httpClient教程.docx_第4页
第4页 / 共22页
httpClient教程.docx_第5页
第5页 / 共22页
点击查看更多>>
下载资源
资源描述

httpClient教程.docx

《httpClient教程.docx》由会员分享,可在线阅读,更多相关《httpClient教程.docx(22页珍藏版)》请在冰豆网上搜索。

httpClient教程.docx

httpClient教程

httpclient教程

  

Commons-httpclient项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。

1.读取网页(HTTP/HTTPS)内容

  最简单的HTTP客户端,用来演示通过GET或者POST方式访问某个页面

Java代码

1.package http.demo;  

2.  

3.import java.io.IOException;  

4.import mons.httpclient.*;  

5.import mons.httpclient.methods.*;  

6.  

7.public class SimpleClient {  

8.  

9.    public static void main(String[] args) throws IOException  

10.    {  

11.        HttpClient client = new HttpClient();     

12.  

13.        //设置代理服务器地址和端口      

14.  

15.        //client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);  

16.  

17.        //使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https  

18.  

19.        HttpMethod method = new GetMethod("");  

20.  

21.        //使用POST方法  

22.  

23.        //HttpMethod method = new PostMethod("");  

24.  

25.        client.executeMethod(method);  

26.  

27.        //打印服务器返回的状态  

28.  

29.        System.out.println(method.getStatusLine());  

30.  

31.        //打印返回的信息  

32.  

33.        System.out.println(method.getResponseBodyAsString());  

34.  

35.        //释放连接  

36.  

37.        method.releaseConnection();  

38.  

39.    }  

40.}  

packagehttp.demo;

importjava.io.IOException;

importmons.httpclient.*;

importmons.httpclient.methods.*;

publicclassSimpleClient{

publicstaticvoidmain(String[]args)throwsIOException

{

HttpClientclient=newHttpClient();

//设置代理服务器地址和端口

//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);

//使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https

HttpMethodmethod=newGetMethod("");

//使用POST方法

//HttpMethodmethod=newPostMethod("");

client.executeMethod(method);

//打印服务器返回的状态

System.out.println(method.getStatusLine());

//打印返回的信息

System.out.println(method.getResponseBodyAsString());

//释放连接

method.releaseConnection();

}

}

2.以GET或者POST方式向网页提交参数

Java代码

1.package http.demo;  

2.  

3.import java.io.IOException;  

4.  

5.import mons.httpclient.*;  

6.  

7.import mons.httpclient.methods.*;  

8.  

9./** 

10. 

11.* 提交参数演示 

12. 

13.* 该程序连接到一个用于查询手机号码所属地的页面 

14. 

15.* 以便查询号码段1330227所在的省份以及城市 

16. 

17.*/  

18.  

19.public class SimpleHttpClient {  

20.  

21.    public static void main(String[] args) throws IOException  

22.  

23.    {  

24.  

25.        HttpClient client = new HttpClient();  

26.  

27.        client.getHostConfiguration().setHost("", 80, "http");  

28.  

29.        HttpMethod method = getPostMethod();//使用POST方式提交数据  

30.  

31.        client.executeMethod(method);  

32.  

33.       //打印服务器返回的状态  

34.  

35.        System.out.println(method.getStatusLine());  

36.  

37.        //打印结果页面  

38.  

39.        String response =  

40.  

41.           new String(method.getResponseBodyAsString().getBytes("8859_1"));  

42.  

43.       //打印返回的信息  

44.  

45.        System.out.println(response);  

46.  

47.        method.releaseConnection();  

48.  

49.    }  

50.  

51.    /** 

52. 

53.     * 使用GET方式提交数据 

54. 

55.     * @return 

56. 

57.     */  

58.  

59.    private static HttpMethod getGetMethod(){  

60.  

61.        return new GetMethod("/simcard.php?

simcard=1330227");  

62.  

63.    }  

64.  

65.    /** 

66. 

67.     * 使用POST方式提交数据 

68. 

69.     * @return 

70. 

71.     */  

72.  

73.    private static HttpMethod getPostMethod(){  

74.  

75.        PostMethod post = new PostMethod("/simcard.php");  

76.  

77.        NameValuePair simcard = new NameValuePair("simcard","1330227");  

78.  

79.        post.setRequestBody(new NameValuePair[] { simcard});  

80.  

81.        return post;  

82.  

83.    }  

84.  

85.}  

packagehttp.demo;

importjava.io.IOException;

importmons.httpclient.*;

importmons.httpclient.methods.*;

/**

*提交参数演示

*该程序连接到一个用于查询手机号码所属地的页面

*以便查询号码段1330227所在的省份以及城市

*/

publicclassSimpleHttpClient{

publicstaticvoidmain(String[]args)throwsIOException

{

HttpClientclient=newHttpClient();

client.getHostConfiguration().setHost("",80,"http");

HttpMethodmethod=getPostMethod();//使用POST方式提交数据

client.executeMethod(method);

//打印服务器返回的状态

System.out.println(method.getStatusLine());

//打印结果页面

Stringresponse=

newString(method.getResponseBodyAsString().getBytes("8859_1"));

//打印返回的信息

System.out.println(response);

method.releaseConnection();

}

/**

*使用GET方式提交数据

*@return

*/

privatestaticHttpMethodgetGetMethod(){

returnnewGetMethod("/simcard.php?

simcard=1330227");

}

/**

*使用POST方式提交数据

*@return

*/

privatestaticHttpMethodgetPostMethod(){

PostMethodpost=newPostMethod("/simcard.php");

NameValuePairsimcard=newNameValuePair("simcard","1330227");

post.setRequestBody(newNameValuePair[]{simcard});

returnpost;

}

}

3.处理页面重定向

详细描述:

状态码 对应HttpServletResponse的常量

301  SC_MOVED_PERMANENTLY 页面已经永久移到另外一个新地址

302  SC_MOVED_TEMPORARILY 页面暂时移动到另外一个新的地址

303  SC_SEE_OTHER 客户端请求的地址必须通过另外的URL来访问

307  SC_TEMPORARY_REDIRECT 同SC_MOVED_TEMPORARILY

下面的代码片段演示如何处理页面的重定向

Java代码

1.client.executeMethod(post);  

2.  

3.System.out.println(post.getStatusLine().toString());  

4.  

5.post.releaseConnection();  

6.  

7.//检查是否重定向  

8.  

9.int statuscode = post.getStatusCode();  

10.  

11.if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||  

12.  

13.    (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||  

14.  

15.    (statuscode == HttpStatus.SC_SEE_OTHER) ||  

16.  

17.    statuscode == HttpStatus.SC_TEMPORARY_REDIRECT))   

18.  

19.  

20.    //读取新的URL地址  

21.  

22.    Header header = post.getResponseHeader("location");  

23.  

24.    if (header !

= null)  

25.    {  

26.  

27.        String newuri = header.getValue();  

28.  

29.        if ((newuri == null) || (newuri.equals("")))  

30.  

31.                   newuri = "/";  

32.  

33.  

34.        GetMethod redirect = new GetMethod(newuri);  

35.  

36.        client.executeMethod(redirect);  

37.  

38.        System.out.println("Redirect:

"+  

39.                 redirect.getStatusLine().toString());  

40.  

41.        redirect.releaseConnection();  

42.  

43.    } else  

44.  

45.         System.out.println("Invalid redirect");  

46.  

47.   }  

client.executeMethod(post);

System.out.println(post.getStatusLine().toString());

post.releaseConnection();

//检查是否重定向

intstatuscode=post.getStatusCode();

if((statuscode==HttpStatus.SC_MOVED_TEMPORARILY)||

(statuscode==HttpStatus.SC_MOVED_PERMANENTLY)||

(statuscode==HttpStatus.SC_SEE_OTHER)||

statuscode==HttpStatus.SC_TEMPORARY_REDIRECT))

{

//读取新的URL地址

Headerheader=post.getResponseHeader("location");

if(header!

=null)

{

Stringnewuri=header.getValue();

if((newuri==null)||(newuri.equals("")))

newuri="/";

 

GetMethodredirect=newGetMethod(newuri);

client.executeMethod(redirect);

System.out.println("Redirect:

"+

redirect.getStatusLine().toString());

redirect.releaseConnection();

}else

System.out.println("Invalidredirect");

}

}

4.模拟输入用户名和口令进行登录

    本小节应该说是HTTP客户端编程中最常碰见的问题,很多网站的内容都只是对注册用户可见的,这种情况下就必须要求使用正确的用户名和口令登录成功后,方可浏览到想要的页面。

因为HTTP协议是无状态的,也就是连接的有效期只限于当前请求,请求内容结束后连接就关闭了。

在这种情况下为了保存用户的登录信息必须使用到Cookie机制。

以JSP/Servlet为例,当浏览器请求一个JSP或者是Servlet的页面时,应用服务器会返回一个参数,名为jsessionid(因不同应用服务器而异),值是一个较长的唯一字符串的Cookie,这个字符串值也就是当前访问该站点的会话标识。

浏览器在每访问该站点的其他页面时候都要带上jsessionid这样的Cookie信息,应用服务器根据读取这个会话标识来获取对应的会话信息。

    对于需要用户登录的网站,一般在用户登录成功后会将用户资料保存在服务器的会话中,这样当访问到其他的页面时候,应用服务器根据浏览器送上的Cookie中读取当前请求对应的会话标识以获得对应的会话信息,然后就可以判断用户资料是否存在于会话信息中,如果存在则允许访问页面,否则跳转到登录页面中要求用户输入帐号和口令进行登录。

这就是一般使用JSP开发网站在处理用户登录的比较通用的方法。

 

    对于HTTP的客户端来讲,如果要访问一个受保护的页面时就必须模拟浏览器所做的工作,首先就是请求登录页面,然后读取Cookie值;再次请求登录页面并加入登录页所需的每个参数;最后就是请求最终所需的页面。

当然在除第一次请求外其他的请求都需要附带上Cookie信息以便服务器能判断当前请求是否已经通过验证。

Java代码

1.package http.demo;  

2.  

3.import mons.httpclient.*;  

4.  

5.import mons.httpclient.cookie.*;  

6.  

7.import mons.httpclient.methods.*;  

8.  

9./** 

10. 

11.* 用来演示登录表单的示例 

12. 

13.*/  

14.  

15.public class FormLoginDemo {  

16.  

17.    static final String LOGON_SITE = "localhost";  

18.  

19.    static final int    LOGON_PORT = 8080;  

20.  

21.     

22.  

23.    public static void main(String[] args) throws Exception{  

24.  

25.        HttpClient client = new HttpClient();  

26.  

27.        client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);  

28.  

29.        

30.  

31.       //模拟登录页面login.jsp->main.jsp  

32.  

33.        PostMethod post = new PostMethod("/main.jsp");  

34.  

35.        NameValuePair name = new NameValuePair("name", "ld");      

36.  

37.        NameValuePair pass = new NameValuePair("password", "ld");      

38.  

39.        post.setRequestBody(new NameValuePair[]{name,pass});  

40.  

41.       int status = client.executeMethod(post);  

42.  

43.        System.out.println(post.getResponseBodyAsString());  

44.  

45.        post.releaseConnection();  

46.  

47.        

48.  

49.       //查看cookie信息  

50.  

51.        CookieSpec cookiespec = CookiePolicy.getDefaultSpec();  

52.  

53.        Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());  

54.  

55.       if (cookies.length == 0) {  

56.  

57.           System.out.println("None");     

58

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 总结汇报 > 学习总结

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1