0

在我的android项目中,我遇到了问题。(即)有时没有从服务器获得响应。我使用 Urlconnection 类连接到服务器。

URL myURL = new URL(url);
        URLConnection conn = myURL.openConnection();

        InputStream is = conn.getInputStream();



        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String line = "";
        StringBuilder sb = new StringBuilder();
        while ((line = in.readLine()) != null) {
            sb.append(line + "\n");
            Log.v("response is .....",
                    "=================Response===================="
                            + sb.toString());

        }

        in.close();
4

1 回答 1

0

最好使用 HTTpURLConnection 并且在获取流之后更好地检查连接是否成功,我认为这可能会对您有所帮助。

URL myURL = new URL(url);

    HttpsURLConnection conn = (HttpsURLConnection) myURL.openConnection();

    InputStream is = conn.getInputStream();
    if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String line = "";
        StringBuilder sb = new StringBuilder();
        while ((line = in.readLine()) != null) {
            sb.append(line + "\n");
            Log.v("response is .....",
                    "=================Response===================="
                            + sb.toString());
        }
    } else {
        Log.v("response is .....", "Wrong response Code from server :"
                + conn.getResponseCode());

    }
    is.close();
    conn.disconnect();
于 2013-11-06T06:14:35.240 回答