I want to send a URL such as "http://192.168.1.1/key_on" to an HTML form and then receive a number 1 or 0 as response, if it can changes correctly, then do something in my app. I send my request by AsyncTask, and it works correctly! But I don't know how to get response ?
Here is my some code in Activities:
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;
And in 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..
}
}
onPostExecute
is fordoInBackground()
method. You will get response string inonPostExecute()
method. So use theresult
string variable as your output.