c62ccb462113e4671a43de169858027e4da2ade6.svn-base
2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.phxl.common.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class XMLClient {
private static HttpClient client;
public static void main(String[] args) throws Exception {
XMLClient client = new XMLClient();
String url = "http://localhost:8080/upload/bookInfo/sendxml5";
//发送XML数据到服务
String result = client.sendXMLDataByPost(url, client.getXMLString(),"text/xml");
System.out.println(result);
}
// 获取XML
public String getXMLString() {
String XML_HEADER = "<?xml version=\"1.0\" encoding=\"GBK\"?>";
StringBuffer sb = new StringBuffer();
sb.append(XML_HEADER);
sb.append("<a>");
sb.append("<b>");
sb.append("<c>");
sb.append("DWMC");
sb.append("</c>");
sb.append("<d>");
sb.append("id=10");
sb.append("</d>");
sb.append("</SELECT>");
sb.append("</b>");
sb.append("</a>");
String mytext = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><book><id>1</id><name>王森勇</name><author>tiger</author></book>";
// 返回String格式
return mytext.toString();
}
// 使用POST方法发送XML数据LL
public static String sendXMLDataByPost(String url, String xmlData, String contentType) throws Exception {
if (client == null){
client = HttpClients.createDefault();
}
HttpPost post = new HttpPost(url);
//post.setHeader("Content-Type","text/xml;charset=UTF-8");
post.setHeader("Content-Type", ""+contentType+";charset=utf-8");
// List<BasicNameValuePair> parameters = new ArrayL ist<BasicNameValuePair>();
//.add(new BasicNameValuePair("text/xml", xmlData));
// post.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8"));
StringEntity entity1 = new StringEntity(xmlData,"UTF-8");
post.setEntity(entity1);
HttpResponse response = client.execute(post);
System.out.println(response.toString());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
return result;
}
}