当前位置: 代码迷 >> J2EE >> *HttpClient+dom4j 有关问题*
  详细解决方案

*HttpClient+dom4j 有关问题*

热度:775   发布时间:2016-04-22 03:45:30.0
************HttpClient+dom4j 问题**************
请问 谁有HttpClient+dom4j代码 或者小例子
请问 他俩在一起怎么写 怎么配置啊!
小弟最高100分 帮帮忙了

------解决方案--------------------
不知道您用的httpclient是什么版本的,我当时用的是httpclient-4.0-alpha3, 我记得NameValuePair应该是用来传递参数的。

HttpPost httpost = new HttpPost("http://127.0.0.1/test.jsp");

NameValuePair[] nvps = 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的,应该有提到这个类吧
------解决方案--------------------
public class ElementalHttpPost {

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

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");
  相关解决方案