使用httpurlconnection设置http标头

时间:2018-07-09 18:54:49

标签: java android http httpurlconnection

嗨,我在设置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)

我该如何解决?预先感谢!

1 个答案:

答案 0 :(得分:1)

这是解决方案:

 BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));