代码可以找到,但它没有返回正确的HTTPRESPONSE,它假设返回成功!作为回应,而是返回一些胡言乱语。这是我的代码,请帮助我,我尝试了很多东西,但没有任何事情发生,请建议。
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;
}
}
答案 0 :(得分:0)
你不能简单地将HTTPResponse转换为String,你需要将它读入输入流或类似的,给出
替换:
result = response.toString();
与
result = EntityUtils.toString(response);
一个去。
答案 1 :(得分:0)
响应不仅在某些时候是String类型,它也可以是二进制,我建议你应该从inputstream中检索内容
HttpEntitiy entitiy = response.getEntity();
Inputstream inputstream = entitiy.getContent();
//do what you want, e.g. convert to string or decode as bitmap