HttpURLConnection .getInputStream()停止工作

时间:2016-11-20 10:04:39

标签: android httpurlconnection inputstreamreader

我正在创建一个Android项目,其中ActivityMain使用HttpURLConnection连接到PHP文件(在本地服务器中,localhost);

我遇到以下代码行的问题:

bufferedReader = new BufferedReader(new InputStreamReader((conn.getErrorStream())));

当我运行项目时,应用程序此时停止,不会返回任何错误。

问题出在哪里?

我在这里报告代码部分:

public class SendToLogin extends AsyncTask<String, Object, String> {

//private EditText usernameField,passwordField;
private String username, password;
private Context context;
private Boolean loggato = false;
JSONObject rspJ;


public SendToLogin(String usr, String psw, Context c) {
    username = usr;
    password = psw;
    context = c;
}

@Override
protected void onPreExecute() {

}

@Override
protected String doInBackground(String... params) {
    String link = params[0] + "?username=" + username.toString() + "&password=" + password.toString();
    URL url = null;
    HttpURLConnection conn = null;
    BufferedReader bufferedReader = null;
    String result = "";
    String line = "";
    try {

        url = new URL(link);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setReadTimeout(1000);
        conn.setDoInput(true);
        int status = conn.getResponseCode();


        bufferedReader = new BufferedReader(new InputStreamReader((conn.getErrorStream())));

        while ((line = bufferedReader.readLine()) != null) {
            result += line + "\n";
        }
        bufferedReader.close();
        return result;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPostExecute(String s) {
    //super.onPostExecute(aVoid);
    String result = s;
    JSONObject reader = null;
    try {
        reader = new JSONObject(result);
        String query_result = reader.getString("msg");
        if(query_result.toString() == "ok")
            new ListaUtenti();
        else {
            Toast loginErrorToast = Toast.makeText(context, "Errore! login errato!", Toast.LENGTH_SHORT);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    //new ReceiveToLogin().execute();

}

}

(当我使用浏览器测试时,php代码返回正确的JSON行)

谢谢你。

3 个答案:

答案 0 :(得分:0)

您需要在获取信息流之前致电conn.connect()

conn.connect(); // connect before getting stream
bufferedReader = new BufferedReader(new InputStreamReader((conn.getInputStream())));

此外,您还要从null返回doInBackground,并且您在onPostExecute中没有空检查,如果是NullPointerException,则会导致reader = new JSONObject(result); @Override protected void onPostExecute(String s) { //super.onPostExecute(aVoid); String result = s; // check null here. JSONObject reader = null; 背景中的例外。

{{1}}

答案 1 :(得分:0)

我跟随here下面的代码并且它对我工作正常

// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

    // Makes sure that the InputStream is closed after the app is
    // finished using it.
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}

请参阅控制台以获取响应代码和响应

答案 2 :(得分:0)

  1. conn.getErrorStream()应为conn.getInputStream(),如@mallaudin所述
  2. super.onPostExecute(aVoid);不应该被评论。它应该是super.onPostExecute(s);
  3. 在java字符串中,比较与query_result.toString().equals('ok')不同,不像query_result.toString()=='ok'
  4. 您可以记录status变量而不是评论吗?