从http android接收响应

时间:2016-07-19 13:00:18

标签: java android android-asynctask httpresponse getresponse

我想发送一个网址,例如" http://192.168.1.1/key_on"到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..
    }
}

1 个答案:

答案 0 :(得分:0)

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