Getting an ajax response in java from a web method (java.io.FileNotFoundException)

假如想象 提交于 2019-12-25 02:18:55

问题


Don't know how to explain it better but i'm trying to get a response from an URL containing a function (right?).

I'm working on this for a lot of hours and progressing a little every time but can't get this finally working. This is the request and response headers from chrome dev tools:

Headers

My code is:

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());

I get the exception (I see in the stack trace) when calling "getinputstream" on this line:

String answer = readStream(conn.getInputStream());

before entering the readStream function!

I don't know how to solve it...

Tried searching about xmlhttprequest but understood that it's only in JS.

Also: I know I have a lot of unnecessary request properties but I can't figure out which are unnecessary until the code will work. Thanks in advance :)


回答1:


Sadly, it used to be (and probably still is) that the HttpURLConnection throws a FileNotFoundException when you get a 404 error. When you are doing the getInputStream() that's when it's first connecting, so any error from the server will show up there.

Get Wireshark or something if you want to see what's really going on in HTTP land as you make the request.



来源:https://stackoverflow.com/questions/8639068/getting-an-ajax-response-in-java-from-a-web-method-java-io-filenotfoundexceptio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!