使用httpurlconnection设置http标头

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

我该如何解决?提前致谢!


PIPIONE
浏览 322回答 1
1回答

肥皂起泡泡

解决方法如下: BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java