I am trying to use the following code to retrieve a response from a server echoed through PHP. The string compare methods compareTo() and (...).equals(..) do not act properly when this code is executed. I have tried all sorts of options and I'm convinced that in spite of appearing to convert the response to string format, "responseText" does not have the typical string properties. If I have 3 string literal statements, one of which is echoed from findUser.php. How can I read it into java in a way that will allow me to determine the contents of the string as i am trying to do here? I have found a lot of discussion about needing to create BufferedReader object, but I do not understand how to implement that. If someone would please lay out the steps for me, I would be very appreciative.
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 || resp开发者_C百科onseText.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());}
}
If your responseText
log message looks correct but the comparison methods are returning false, then you likely have a character set issue. There are many cases of what appears to be the same character appearing at different code points of different character sets.
The documentation for EntityUtils.toString() states that when no character set is specified, it tries to analyse the entity or just falls back to ISO-8859-1.
UTF-8 is generally a safe default to use. Try adding this to the top of your PHP script:
<?php
header('Content-Type: text/plain; charset=utf-8');
?>
EntityUtils should pick that up, if not you can pass "utf-8" to the toString() method to force it to use the same character set.
Here are a couple more ways to read data from a response.
InputStream inputStream = response.getEntity().getContent();
(Method 1) Read data one line at a time using a buffered reader
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String readData = "";
String line = "";
while((line = br.readLine()) != null){
readData += line;
}
(Method 2) Read data one byte at a time, then convert to string
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);
精彩评论