0

我正在尝试发送请求以获取公共交通信息。这是下面示例的屏幕截图,说明我必须向站点发送 XML 请求,定义方法和服务引用(在示例中是 StopMonitoringRequest 和 020035811)。

指示

到目前为止,我已经设法连接到该服务,但我不知道从这里做什么。到目前为止,我已经这样做了...

String user = "";
String pass = "";                        
String url = "http://nextbus.mxdata.co.uk/nextbuses/1.0/1";

String authString = user + ":" + pass;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);

HttpURLConnection  connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestMethod("POST");
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty( "charset", "utf-8");
connection.setUseCaches(false);
connection.setDoOutput(true);

InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);

int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
    sb.append(charArray, 0, numCharsRead);
}

String result = sb.toString();
System.out.print(result);

...收到这个:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Siri version="1.0" xmlns="http://www.siri.org.uk/">
<ServiceDelivery>
<ResponseTimestamp>2015-11-08T20:33:03.574Z</ResponseTimestamp>
</ServiceDelivery>
</Siri>

如何输入所需的参数和方法?

4

1 回答 1

0

所以我要做的是创建一个 HttpPost 并将 xml 请求设置为一个实体,将其绑定到帖子。下面是代码,以防有人想使用 XML 通过 HTTP POST 请求信息,将 XML 输出为字符串:

// basic autthorization security 
String url = "http://nextbus.mxdata.co.uk/nextbuses/1.0/1";
String authString = "<username>:<password>";
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);

DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "Basic " + authStringEnc);
StringEntity input = new StringEntity(request);
input.setContentType("text/xml");
post.setEntity(input);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String unformattedXML = EntityUtils.toString(entity);
于 2015-11-16T11:45:11.697 回答