使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据

 

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 

2010-06-22 00:10:26|  分类: http协议 |  标签: |字号 订阅

案例需求简单描述:

需要发送一个XML格式的数据,通过HTTP请求并以POST方式到达"服务器端", 服务器端暂时只返回状态码,客户端通过判断状态码检查这次请求是否成功.


之前写过使用Socket套接字连接发送请求,也有通过URLConnection等方式,但是时间久了忘记怎么写了也要去查API,查来查去就查到了HTTPClient. 目前本人使用的是 HTTP Client 4.0.1 API .

至于HttpClient,HttpCore等是什么,简单来说就是一层封装的API,简化了我们发送请求和解析请求以及处理请求和响应的代码.

大家可以到这个地址上去查看Apache提供的API和源代码,关于他们的介绍上面也说的很清楚了.

http://hc.apache.org/

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 - lvp - Java Log

The Hyper-Text Transfer Protocol (HTTP) is perhaps the most significant protocol used on the Internet today. Web services, network-enabled appliances and the growth of network computing continue to expand the role of the HTTP protocol beyond user-driven web browsers, while increasing the number of applications that require HTTP support.

Designed for extension while providing robust support for the base HTTP protocol, the HttpComponents may be of interest to anyone building HTTP-aware client and server applications such as web browsers, web spiders, HTTP proxies, web service transport libraries, or systems that leverage or extend the HTTP protocol for distributed communication.


简单环境的配置

需要的jar文件可以在http://hc.apache.org/downloads.cgi 地址下载,

HttpClient 4.0.1 (GA)  其中有一个选项

Binary with dependencies ,下载它的zip包,自己解压缩后寻找lib目录,拷贝到自己的项目中或者以附加的形式即可.

其核心的jar包是 :

httpclient-4.0.1.jar                    httpcore-4.0.1.jar                 httpmime-4.0.1.jar

其它的是依赖的jar包

commons-logging-1.1.1.jar      commons-codec-1.3.jar        apache-mime4j-0.6.jar

由于目前网易博客中没有提供上传和下载功能,所以我使用网易的网盘,把这几个相关的资源发布出来,建议能看懂官方文档的还是去官方文档中找找需要下载哪些东西.

http-client-4.0.1-src.zip http-client src 源代码压缩文件,

http-core-4.0.1-src.zip http-core src 源代码ZIP

http-client-core-lib 相关的几个jar文件,上面提到的JAR包都在这个压缩文件中,从此文件的lib文件夹中就可以找到

通常要看哪一个类的源代码,按下ctrl键,鼠标移上去点击这个类即可,如果这个类没有绑定到源代码,是看不见的,就需要你自己 attach source ,然后选中浏览自己电脑中的源代码.zip,就可以在MyEclipse中直接查看源代码了.

2010年06月24日 注释 // 昨天还是可以下载的,但是今天就不能使用下载了...所以无法下载.


以下是代码的示例,目前还未真正测试过服务器端到底能不能接受到这次请求数据,只是简单观察了下 TCP/IP Monitor, 后期会投入一定的时间继续深入这套API组件.

IClient.java

package com.apt.client;

/**
* Constant Interface to define the normal Constant in this application
*
* @author Lv Pin
*
*/

public interface IClient {

     /**
      * The XML Header of every XML string
     */
      public String XML_HEADER = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
}

XMLClient.java

package com.apt.client;

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

/**
* HTTP Client, to send data of XML type to Server. This is a demonstration of
* how to use HTTP Client API
*
* @author Lv Pin
*
*/
public class XMLClient {

  /**
    * HTTP Client Object,used HttpClient Class before(version 3.x),but now the
    * HttpClient is an interface
    */
   private DefaultHttpClient client;

  /**
     * Get XML String
     *
     * @return XML-Formed string
   */
public String getXMLString() {
// A StringBuffer Object
  StringBuffer sb = new StringBuffer();
  sb.append(IClient.XML_HEADER);
  sb.append("<AastraIPPhoneInputScreen type=\"string\">");
  sb.append("<Title>Hello world!</Title>");
  sb.append("<Prompt>Enter value</Prompt>");
  sb.append("<URL>http://localhost/xmlserver/test.do</URL>");
  sb.append("<Parameter>value</Parameter>");
  sb.append("<Default></Default>");
  sb.append("</AastraIPPhoneInputScreen>");
// return to String Formed
  return sb.toString();
}

/**
  * Send a XML-Formed string to HTTP Server by post method
  *
  * @param url
  *            the request URL string
  * @param xmlData
  *            XML-Formed string ,will not check whether this string is
  *            XML-Formed or not
  * @return the HTTP response status code ,like 200 represents OK,404 not
  *         found
  * @throws IOException
  * @throws ClientProtocolException
  */
public Integer sendXMLDataByPost(String url, String xmlData)
   throws ClientProtocolException, IOException {
  Integer statusCode = -1;
  if (client == null) {
   // Create HttpClient Object
   client = new DefaultHttpClient();
  }
// Send data by post method in HTTP protocol,use HttpPost instead of
  // PostMethod which was occurred in former version
  HttpPost post = new HttpPost(url);
// Construct a string entity
  StringEntity entity = new StringEntity(xmlData);
  // Set XML entity
  post.setEntity(entity);
  // Set content type of request header
  post.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
// Execute request and get the response
  HttpResponse response = client.execute(post);
  // Response Header - StatusLine - status code
  statusCode = response.getStatusLine().getStatusCode();
  return statusCode;
}

/**
  * Main method
  * @param args
  * @throws IOException
  * @throws ClientProtocolException
  */
public static void main(String[] args) throws ClientProtocolException, IOException {
  XMLClient client = new XMLClient();
  Integer statusCode = client.sendXMLDataByPost("http://localhost:8081", client.getXMLString());
  if(statusCode==200){
   System.out.println("Request Success,Response Success!!!");
  }else{
   System.out.println("Response Code :"+statusCode);
  }
}
}


测试步骤:

1. 启动Tomcat,我目前Tomcat默认的端口号是 8080 .

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 - lvp - Java Log

2. Window - Show View 中搜索 TCP/IP Monitor

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 - lvp - Java Log

3. 看TCP/IP Monitor界面 ,在它的空白处点击右键 Properties

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 - lvp - Java Log

4.配置 Monitor. 点击Add

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 - lvp - Java Log

5. 新建一个监控, 要说明的是我刚才请求的是Tomcat的主页  http://localhost:8080 , 现在准备测试的也是通过我自己的客户端

程序去发送一个请求到  http://localhost:8080 ,不管合理与不合理,只管发送看看是否成功,是否有数据出去即可.

在这里我们要实际检测的是 Monitor :

Host name - localhost

Port - 8080

Type - HTTP

但是我们需要在本地映射一个端口,即客户端去请求这个映射的端口时,那么我们这个Monitor就会起作用了,并且它也

映射到了实际的端口.

所以在Local monitoring port 中填写:8081 ,即我们在使用Monitor测试时请求这个端口,Monitor监测我们的请求,并把

这次请求映射到实际的 8080端口上去.

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 - lvp - Java Log

6. 别忘记了 要Start.Monitor...同时再次提醒Tomcat的服务也要启动起来

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 - lvp - Java Log

7. 看代码中请求的是 http://localhost:8081 而不是 8080, 因为有Monitor在监测并映射,所以我们的请求会成功,监测也会起作用

     运行这个代码,不出意外,应该是输出 "Request Success,Response Success!!!",因为响应的状态码是 200

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 - lvp - Java Log

8. 输出结果

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 - lvp - Java Log

9. 查看TCP/IP Monitor 中发生的变化,单击小斜杠 "/"

     左侧的是Request,说明的是发送请求的数据

     左侧上方块是 请求头信息, 特别明显的是 POST / HTTP/1.1   POST方式,请求的是 /(根目录) 协议HTTP1.1

     下方是 发送XML格式字符串数据.

     右侧的是Response的数据, 很醒目的是HTTP/1.1 200 OK, 响应成功.

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 - lvp - Java Log

10. 改改代码 去请求 /error.jsp 会看到这样的结果.  Response中 404 - Page Not Found

使用HttpClient通过POST方式发送XML,使用TCP/IP Monitor观察数据 - lvp - Java Log

 


只是一个初步的使用的测试案例,以往懒惰于总结和记录,以至于用时丢三拉四,这次会逐步把使用过的东西都总结和记录下来,便于自我学习查阅和分享与他人.

且会逐步在此基础上去丰富内容,更正错误.

评论这张
转发至微博
转发至微博
0 分享到:
阅读(2361) | 评论(1) | 引用 (1) | 举报
历史上的今天
评论
登录后你可以发表评论,请先登录。 登录>>
2011-08-03 16:24

不错,收藏了

回复
上一页 1... -1-1-1-1-1-1-1 ... -1 下一页
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值