简体   繁体   中英

receive response from http android

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..
    }
}

请检查您的请求网址( http://192.168.1.1/key_off )得到404错误代码。请在网络中触发您的网址。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM