我有一个我想用来获取数据的API。为了获取数据,我必须以XML格式发送请求,并且将以XML格式发送响应。有没有人有任何示例如何使用Java发送请求以及如何解码java中的响应。
答案 0 :(得分:2)
嗯,我有你想要的......但我会要求你使用以下API ......
JAXP
和JAXB
Castor
- 以下代码段方法接受网络服务器的url
和xmlQuery
- 我已使用NameValuePair
发送XML请求
- 请替换 MySSLSocketFactory.getNewHttpClient();
与Http
客户端,我使用过它需要自定义证书才能访问此网站。
以下是我的Project中的代码,它发送XML req并获取XML resp:
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();
}
答案 1 :(得分:0)
查看以下讨论,How to send HTTP request in java? 对于xml中的响应,请确保将mime-type设置为application / xml。 希望这能回答你的问题。