You cannot simply convert a HTTPResponse to a String, you'll need to read it into an input stream or similar, give
Replace:
result = response.toString();
with
result = EntityUtils.toString(response);
a go.
题
The code works find but its not returning the right HTTPRESPONSE it suppose to return Success! as a response but instead is returning some gibberish. Here is my code please help me out I tried so many things but nothing is happening please advice.
public class PingServerActivity extends Activity {
private Button btn6;
//private EditText value;
protected String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ping_server);
btn6 = (Button) findViewById(R.id.btn_6);
//value = (EditText) findViewById(R.id.textV5);
pingButton();
}
public void pingButton() {
btn6.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// this button would send the request to the server
new PingPostTask().execute(new String[] {name});
}
});
}
private class PingPostTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params)
{
BufferedReader inBuffer = null;
String url = "http://ec2-54-243-205-92.compute-1.amazonaws.com/Tests/ping.php";
String result = "fail";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("Password", "EGOT"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
request.setEntity(formEntity);
HttpResponse response = httpClient.execute(request);//btw, i'm NOT very sure if this will work LOL
result = response.toString();
} catch(Exception e) {
// Do something about exceptions
result = e.getMessage();
} finally {
if (inBuffer != null) {
try {
inBuffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
protected void onPostExecute(String result)
{
//textView.setText(page);
Toast toast = Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG);
toast.show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.ping_server, menu);
return true;
}
}
解决方案
You cannot simply convert a HTTPResponse to a String, you'll need to read it into an input stream or similar, give
Replace:
result = response.toString();
with
result = EntityUtils.toString(response);
a go.
其他提示
The response not only a String type in some times, it can also be a binary, I suggest you should retrieve the content from inputstream
HttpEntitiy entitiy = response.getEntity();
Inputstream inputstream = entitiy.getContent();
//do what you want, e.g. convert to string or decode as bitmap