Java 使用HttpClient写入正文请求
我想用XML内容类型编写请求体,但不知道如何使用HttpClient对象()Java 使用HttpClient写入正文请求,java,xml,request,apache-httpclient-4.x,Java,Xml,Request,Apache Httpclient 4.x,我想用XML内容类型编写请求体,但不知道如何使用HttpClient对象() 我不知道如何继续用我的XML编写正文…如果您的XML是由java.lang.String编写的,您可以这样使用HttpClient public void post() throws Exception{ HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.ba
我不知道如何继续用我的XML编写正文…如果您的XML是由
java.lang.String
编写的,您可以这样使用HttpClient
public void post() throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.baidu.com");
String xml = "<xml>xxxx</xml>";
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
}
public void post()引发异常{
HttpClient=new DefaultHttpClient();
HttpPost=新的HttpPost(“http://www.baidu.com");
字符串xml=“xxxx”;
HttpEntity=newbytearrayentity(xml.getBytes(“UTF-8”);
后设实体(实体);
HttpResponse response=client.execute(post);
字符串结果=EntityUtils.toString(response.getEntity());
}
注意例外情况
顺便说一句,该示例是由扩展代码的httpclient版本4.x编写的(假设要发送的XML位于xmlString
):
String xmlString=”“;
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost-httpRequest=新的HttpPost(this.url);
setHeader(“内容类型”、“应用程序/xml”);
StringEntity xmlEntity=新的StringEntity(xmlString);
httpRequest.setEntity(xmlEntity);
HttpResponse HttpResponse=httpclient.execute(httppost);
我建议使用java.nio.charset.StandardCharsets
,并将ByteArrayEntity
行修改为:HttpEntity entity=newbytearrayentity(xml.getBytes(StandardCharsets.utf8));而不是newbytearrayentity(xml.getBytes(“UTF-8”)代码>使用新的StringEntity(xml,ContentType.APPLICATION\uXML)代码>使用新的StringEntity可能会导致标头中声明的字符集不正确。小心使用。应改用,因为DefaultHttpClient
已弃用。
public void post() throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.baidu.com");
String xml = "<xml>xxxx</xml>";
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
}
String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);