【发布时间】:2011-12-26 20:58:41
【问题描述】:
不知道如何更好地解释它,但我正在尝试从包含函数的 URL 获得响应(对吗?)。
我为此工作了很多小时,每次都取得了一点进步,但最终无法让它发挥作用。 这是来自 chrome 开发工具的请求和响应标头:
我的代码是:
String params = "{\"prefixText\":\"" + city
+ "\",\"count\":10,\"contextKey\":\"he\"}";
conn = (HttpURLConnection) new URL(
"http://bus.gov.il/WebForms/wfrmMain.aspx/GetCompletionList")
.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setChunkedStreamingMode(0);
// conn.setFixedLengthStreamingMode(params.length());
conn.addRequestProperty("Accept", "*/*");
conn.addRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.addRequestProperty("Content-Length", String.valueOf(params.length()));
conn.addRequestProperty("Host", "bus.gov.il");
conn.addRequestProperty("Origin", "http://bus.gov.il");
conn.addRequestProperty("X-Requested-With", "XMLHttpRequest");
conn.addRequestProperty("Referer",
"http://bus.gov.il/WebForms/wfrmMain.aspx?width=1024&company=1&language=he&state=");
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(params.getBytes());
String answer = readStream(conn.getInputStream());
在这一行调用“getinputstream”时出现异常(我在堆栈跟踪中看到):
String answer = readStream(conn.getInputStream());
进入readStream函数之前!
不知道怎么解决……
尝试搜索有关 xmlhttprequest 但知道它仅在 JS 中。
另外:我知道我有很多不必要的请求属性,但在代码运行之前我无法弄清楚哪些是不必要的。 在此先感谢:)
【问题讨论】:
-
工作代码(如果有人需要):pastebin.com/kFZwA5zR
标签: java android ajax httpurlconnection