我想将诸如“ http://192.168.1.1/key_on ”之类的 URL 发送到 HTML 表单,然后接收数字 1 或 0 作为响应,如果它可以正确更改,则在我的应用程序中执行某些操作。我通过 AsyncTask 发送我的请求,它工作正常!但我不知道如何得到回应?
这是我在活动中的一些代码:
Button btn= (Button)convertView.findViewById(R.id.two);
btn.setWidth(500);
new RequestTask().execute("http://192.168.1.1/key_on");
btn.setBackgroundColor(Color.parseColor("#FF11AC06"));
btn.setText(childText);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int color = Color.TRANSPARENT;
Drawable background = view.getBackground();
if (background instanceof ColorDrawable)
color = ((ColorDrawable) background).getColor();
if (color == Color.parseColor("#FF11AC06")) {
new RequestTask().execute("http://192.168.1.1/key_off");
view.setBackgroundColor(Color.parseColor("#FF41403F"));
} else {
view.setBackgroundColor(Color.parseColor("#FF11AC06"));
new RequestTask().execute("http://192.168.1.1/key_on");
}
}
});
return convertView;
在 RequestTask.java 中:
class RequestTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}