在Java中XML请求/响应 [英] XML request/response in Java
问题描述
我有我想要使用来获取数据的API。为了获取数据我要送XML格式和响应的请求将XML发送。没有人有任何例如如何发送使用Java和如何去code在Java中响应的请求。
I have an API which I want to use to fetch data. For fetching data I have to send a request in XML format and response will be sent in XML. Does anyone have any example how to send a request using Java and how to decode the response in java.
推荐答案
嗯,我有你想要的正是...但我会要求您使用以下API ...
Well i have just what you wanted... but i would ask you to use the following APIs ...
-
JAXP
和JAXB
-
蓖麻
JAXP
andJAXB
Castor
- 以下code段方法接受网址
web服务器和 XMLQUERY <的/ code>
- The below code snippet method accepts the url
of the web-server and the xmlQuery
- 我已经使用了的NameValuePair </ code>发送XML请求
- I have used the NameValuePair
to send the XML request
- 请替换的 MySSLSocketFactory.getNewHttpClient();
与 HTTP
客户端,我已经使用这个需要自定义证书访问此site.`
- Please replace the MySSLSocketFactory.getNewHttpClient();
with an Http
Client, i have used this it needs a custom certificate to access this site.`
这是从我的项目,发送一个XML REQ和回来一个XML RESP的code:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = MySSLSocketFactory.getNewHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now", sb + "");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method " + sb.toString());
return sb.toString();
}
这篇关于在Java中XML请求/响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!