Dom4j和HttpClient是jakarta.apache.org的一个子项目(不知道是不是,胡乱瞎掰)到这里
http://jakarta.apache.org/site/downloads/downloads_commons.html可以看到它的最新的包(“它”是指jakarta.apache.org)。Dom4j的用法有个前辈已经提到了,在这里我就不用在献丑了,感兴趣可以去 http://zrhett.blogchina.com/1041766.html 看看。好了,言归正传,来说说他们2个怎么配合的。要使用HttpClient的话还要另外2个哥们支持他才行,他们就是commons-codec和commons-logging包。有了他们2兄弟的支持HttpClient才能很好的工作。HttpClient既然是一个包,那么里面就有一些类和方法供我们调用。其他的方法先不说,要使用HttpClient就要首先实例化一个对象,即:HttpClient client = new HttpClient();然后再实例一些方法,比如:MultipartPostMethod mp = new MultipartPostMethod(url);url是你需要发送的目的地。当要执行这个方法的时候就需要第一次实例话的client来执行它:client.executeMethod(mp);当然,你还可以在你实例化的方法MultipartPostMethod中新建参数:mp.addParameter("requestxml",xml);来发送一些信息,就像表单里面的元素一样。现在有个WebService或者其他的什么东西,能提供一个应答机制的服务。你有什么请求就按照它给定的xml格式封装穿给它,它再把它回复你的讯息也是用过xml封装传回给你,当然,这里的格式都是大家都知道的。刚才我们说的那个HttpClient建立了一个MultipartPostMethod方法,并且增加了一个元素:requestxml,它的值是一个字符串xml,里面就是一个xml文件(当然也可把整个xml文件一起传送给服务器端),发送到服务器:HttpClient client = new HttpClient();MultipartPostMethod mp = new MultipartPostMethod(url); mp.addParameter("requestxml",xml); client.executeMethod(mp);需要接收服务器端传回来的内容的时候使用MultipartPostMethod的getResponseBodyAsStream()接口或者getResponseBodyAsString()接口。有了这个回传的信息过后就该我们的dom4j来露一手了:SAXReader reader = new SAXReader(); Document document = reader.read(mp.getResponseBodyAsStream()); Element root = document.getRootElement(); List mylist = root.selectNodes(path);path是xml的节点路径,比如有一个xml文件是这样的:<root><data><games><game><name>魔兽世界</name><type>网络游戏</type></game><game><name>仙剑奇侠传</name><type>单机游戏</type></game></games>如果path=”//root/games/game”那么,就是说要遍历path下面的所有子节点了。
在刚才的代码上加上:
Iterator iter = mylist.iterator(); while(iter.hasNext()){ Element element = (Element)iter.next();System.out.println(element.selectNode(”name”).getText());System.out.println(element.selectNode(”type”).getText());}那么就可以列出“魔兽世界”、“网络游戏”、“仙剑奇侠传”、“单机游戏了”。
http://jakarta.apache.org/site/downloads/downloads_commons.html可以看到它的最新的包(“它”是指jakarta.apache.org)。Dom4j的用法有个前辈已经提到了,在这里我就不用在献丑了,感兴趣可以去 http://zrhett.blogchina.com/1041766.html 看看。好了,言归正传,来说说他们2个怎么配合的。要使用HttpClient的话还要另外2个哥们支持他才行,他们就是commons-codec和commons-logging包。有了他们2兄弟的支持HttpClient才能很好的工作。HttpClient既然是一个包,那么里面就有一些类和方法供我们调用。其他的方法先不说,要使用HttpClient就要首先实例化一个对象,即:HttpClient client = new HttpClient();然后再实例一些方法,比如:MultipartPostMethod mp = new MultipartPostMethod(url);url是你需要发送的目的地。当要执行这个方法的时候就需要第一次实例话的client来执行它:client.executeMethod(mp);当然,你还可以在你实例化的方法MultipartPostMethod中新建参数:mp.addParameter("requestxml",xml);来发送一些信息,就像表单里面的元素一样。现在有个WebService或者其他的什么东西,能提供一个应答机制的服务。你有什么请求就按照它给定的xml格式封装穿给它,它再把它回复你的讯息也是用过xml封装传回给你,当然,这里的格式都是大家都知道的。刚才我们说的那个HttpClient建立了一个MultipartPostMethod方法,并且增加了一个元素:requestxml,它的值是一个字符串xml,里面就是一个xml文件(当然也可把整个xml文件一起传送给服务器端),发送到服务器:HttpClient client = new HttpClient();MultipartPostMethod mp = new MultipartPostMethod(url); mp.addParameter("requestxml",xml); client.executeMethod(mp);需要接收服务器端传回来的内容的时候使用MultipartPostMethod的getResponseBodyAsStream()接口或者getResponseBodyAsString()接口。有了这个回传的信息过后就该我们的dom4j来露一手了:SAXReader reader = new SAXReader(); Document document = reader.read(mp.getResponseBodyAsStream()); Element root = document.getRootElement(); List mylist = root.selectNodes(path);path是xml的节点路径,比如有一个xml文件是这样的:<root><data><games><game><name>魔兽世界</name><type>网络游戏</type></game><game><name>仙剑奇侠传</name><type>单机游戏</type></game></games>如果path=”//root/games/game”那么,就是说要遍历path下面的所有子节点了。
在刚才的代码上加上:
Iterator iter = mylist.iterator(); while(iter.hasNext()){ Element element = (Element)iter.next();System.out.println(element.selectNode(”name”).getText());System.out.println(element.selectNode(”type”).getText());}那么就可以列出“魔兽世界”、“网络游戏”、“仙剑奇侠传”、“单机游戏了”。
我现在配置上了 也能解析了 现在又出现一个不动的问题了
这句是什么意思??
NameValuePair name = new NameValuePair("这里是什么意思","这里是什么意思");
越详细越好 谢谢
new BasicNameValuePair("username", "your username"),
new BasicNameValuePair("password", "your password")
};
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();比如你想模拟下面这张网页的submit()方法<form action='xxx.jsp' method='post'>
<type input='text' name='username' value='your username'/>
<type input='text' name='password' value='your password'/>
</form>
... 省略N多,呵呵当你submit这张网页的时候,username和password会被post到下一张网页。而当你用httpclient去模拟submit方法的时候,你就要构建username和password参数了,NameValuePair就是用来构建这一系列参数的。请记得对参数进行编码,就是例子中的"your username" 和 "your password"。httpclient包有很多sample的,应该有提到这个类吧
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
BasicHttpProcessor httpproc = new BasicHttpProcessor();
// Required protocol interceptors
httpproc.addInterceptor(new RequestContent());
httpproc.addInterceptor(new RequestTargetHost());
// Recommended protocol interceptors
httpproc.addInterceptor(new RequestConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {
HttpEntity[] requestBodies = {
new StringEntity(
"This is the first test request", "UTF-8"),
new ByteArrayEntity(
"This is the second test request".getBytes("UTF-8")),
new InputStreamEntity(
new ByteArrayInputStream(
"This is the third test request (will be chunked)"
.getBytes("UTF-8")), -1)
};
for (int i = 0; i < requestBodies.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
"/servlets-examples/servlet/RequestInfoExample");
request.setEntity(requestBodies[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri()); context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
BasicHttpProcessor httpproc = new BasicHttpProcessor();
// Required protocol interceptors
httpproc.addInterceptor(new RequestContent());
httpproc.addInterceptor(new RequestTargetHost());
// Recommended protocol interceptors
httpproc.addInterceptor(new RequestConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {
HttpEntity[] requestBodies = {
new StringEntity(
"This is the first test request", "UTF-8"),
new ByteArrayEntity(
"This is the second test request".getBytes("UTF-8")),
new InputStreamEntity(
new ByteArrayInputStream(
"This is the third test request (will be chunked)"
.getBytes("UTF-8")), -1)
};
for (int i = 0; i < requestBodies.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
"/servlets-examples/servlet/RequestInfoExample");
request.setEntity(requestBodies[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri()); context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
BasicHttpProcessor httpproc = new BasicHttpProcessor();
// Required protocol interceptors
httpproc.addInterceptor(new RequestContent());
httpproc.addInterceptor(new RequestTargetHost());
// Recommended protocol interceptors
httpproc.addInterceptor(new RequestConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {
HttpEntity[] requestBodies = {
new StringEntity(
"This is the first test request", "UTF-8"),
new ByteArrayEntity(
"This is the second test request".getBytes("UTF-8")),
new InputStreamEntity(
new ByteArrayInputStream(
"This is the third test request (will be chunked)"
.getBytes("UTF-8")), -1)
};
for (int i = 0; i < requestBodies.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
"/servlets-examples/servlet/RequestInfoExample");
request.setEntity(requestBodies[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri()); context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
http://jakarta.apache.org/site/downloads/downloads_commons.html可以看到它的最新的包(“它”是指jakarta.apache.org)。Dom4j的用法有个前辈已经提到了,在这里我就不用在献丑了,感兴趣可以去 http://zrhett.blogchina.com/1041766.html 看看。好了,言归正传,来说说他们2个怎么配合的。
1,在HttpClient 将request请求用dom4j写入(request请求需要先定义好,如:用户名用UM代替)
2,在handler端处理请求,将处理结果用dom4j写入response返回。
3,在客户端处理返回。