HttpClient4 Post XML到一个服务器上
2010-08-20 00:00:00 来源:WEB开发网现在网上介绍的HttpClient基本上全是3.x版本的内容,HttpClient4的API变化相对3已经变化很大,对HttpClient4做了简单的研究后,完成了一个HttpClient4 Post XML功能。
对于POST方式,最先想到的就是表单提交了,POST XML自然想到的就是定义一个变量名,比如叫xmldata,然后将这个参数的值POST出去,在服务端接收的时候,自然也是通过 requset.getParameter("xmldata")方式来接收。
现在我在这里要做的不是通过上面的方式,而是不指定参数名来Post,实际上就是将一个流写入请求。
下面是具体的实现方式:
1、参数名方式POST XML数据
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.*;
/**
* 通过指定参数名的方式POST XML
*
* @author leizhimin 2010-7-8 22:29:28
*/
public class TestPost {
public static void main(String[] args) throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8080/waitsrv/GenXmlServlet");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("xmldate", "<html>你好啊啊</html>"));
formparams.add(new BasicNameValuePair("info", "xxxxxxxxx"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "GBK");
// entity.setContentType("text/xml; charset=GBK");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
InputStreamReader reader = new InputStreamReader(resEntity.getContent(), "ISO-8859-1");
char[] buff = new char[1024];
int length = 0;
while ((length = reader.read(buff)) != -1) {
System.out.println(new String(buff, 0, length));
httpclient.getConnectionManager().shutdown();
}
}
}
Tags:HttpClient Post XML
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接