读取从PHP回显到java的字符串


Reading a string echoed from PHP into java?

我正在尝试使用以下代码从通过 PHP 回显的服务器检索响应。 字符串比较方法 compareTo() 和 (...)。equals(..) 在执行此代码时无法正常工作。 我已经尝试了各种选项,我相信尽管似乎将响应转换为字符串格式,但"responseText"没有典型的字符串属性。 如果我有 3 个字符串文字语句,其中一个是从 findUser.php 回显的。 我怎样才能以一种允许我在这里尝试的方式将其读入 java 以确定字符串的内容? 我发现很多关于需要创建 BufferedReader 对象的讨论,但我不明白如何实现它。 如果有人能为我布置步骤,我将不胜感激。

 try {  
      HttpClient httpclient = new DefaultHttpClient();  
      HttpPost httppost = new HttpPost(".../findUser.php");  
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
      HttpResponse response = httpclient.execute(httppost);  
      final String responseText =  EntityUtils.toString(response.getEntity());  

      if(responseText.compareTo("Not Registered") == 0 || responseText.compareTo("Error") == 0) {  
          Log.i("KYLE","TRUE");
          // DISPLAY ERROR MESSAGE  
          TextView loginError = (TextView)findViewById(R.id.loginErrorMsg);  
          loginError.setVisibility(View.VISIBLE);
          loginError.setText(responseText); 
      }  
      else {  
          GlobalVars.username = userEmail;  
          Login.this.finish();  
          Intent intent = new Intent(Login.this,Purchase.class);  
          startActivity(intent);
      }  
      catch(Exception e) {Log.e("log_tag", "Error in http connection"+e.toString());}

}

如果您的responseText日志消息看起来正确,但比较方法返回 false,则可能存在字符集问题。在许多情况下,看似相同的字符出现在不同字符集的不同代码点上。

EntityUtils.toString() 的文档指出,当未指定字符集时,它会尝试分析实体或只是回退到 ISO-8859-1。

UTF-8 通常是安全的默认值。尝试将其添加到 PHP 脚本的顶部:

<?php 
   header('Content-Type: text/plain; charset=utf-8'); 
?>

EntityUtils应该选择它,如果没有,你可以将"utf-8"传递给toString()方法以强制它使用相同的字符集。

以下是从响应中读取数据的更多方法。

InputStream inputStream = response.getEntity().getContent();

(方法 1) 使用缓冲读取器一次读取一行数据

    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    String readData = "";
    String line = "";
    while((line = br.readLine()) != null){
        readData += line;
    }

(方法2)一次读取一个字节的数据,然后转换为字符串

    byte[] buffer = new byte[10000]; //adjust size depending on how much data you are expecting
    int readBytes = inputStream.read(buffer);
    String dataReceived = new String(buffer, 0, readBytes);