【发布时间】:2018-12-17 12:52:33
【问题描述】:
您好,我在设置 http 请求的标头时遇到问题,这是我正在使用的代码
public static JSONObject getJSONObjectFromURL(String urlString, String version, String menuTop, String menuBottom) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("X-Mobile-Version", MessageFormat.format("android/{0}", version));
urlConnection.setRequestProperty("X-Menu-Hash", menuTop);
urlConnection.setRequestProperty("X-MenuBottom-Hash", menuBottom);
urlConnection.setReadTimeout(10000 /* milliseconds */ );
urlConnection.setConnectTimeout(15000 /* milliseconds */ );
urlConnection.setDoOutput(true);
urlConnection.connect();
//Log.d("-------------------....",urlConnection.getRequestProperty("X-Mobile-Version"));
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String jsonString = sb.toString();
Log.d("..........JSon", jsonString);
return new JSONObject(jsonString);
}
但我总是收到以下错误
W/System.err: java.io.FileNotFoundException: endpoint/
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:251)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(Unknown Source:0)
at java.net.URL.openStream(URL.java:1058)
at com.example.bordi.hotel.DataManager.getJSONObjectFromURL(DataManager.java:109)
at com.example.bordi.hotel.DataManager$1.run(DataManager.java:132)
at java.lang.Thread.run(Thread.java:764)
我该如何解决?提前致谢!
【问题讨论】:
-
如果您收到
FileNotFoundException,则表示您尝试下载的 URL 出现 404 错误(或其他 40x 错误之一)。把urlString的值打印出来,贴在这里。 -
我确定 url 工作正常,因为在同一应用程序的 IOS 版本上,我可以从中下载儿子,我认为错误出现在调用的标题中,因为我不确定这是设置它们的正确方法
-
您在设置什么标题时遇到什么问题?注意 URL 肯定不起作用:@LeoAso 非常正确。显然 URL 不是你想的那样。你为什么要在 GET 请求中调用
setDoOutput(true)?然后不做任何输出?您正在将其转换为不带参数的 POST 请求。 -
@EJP 为了使 url 工作我必须设置三个标题:X-Mobile-Version、X-Menu-Hash 和 X-MenuBottom-Hash,我使用我拥有的代码设置它们已经粘贴但显然我以错误的方式设置它们,因为 url 不起作用,我的问题是:这是设置 httheader 的正确方法吗?
-
你在草率下结论。错误地设置标题不会导致 404 错误。第三次,这里的问题是 URL(
endpoint/: 在我看来不正确),以及我提到的所有其他内容。
标签: java android http httpurlconnection