【问题标题】:receive response from http android接收来自 http android 的响应
【发布时间】:2016-07-19 13:00:17
【问题描述】:

我想将诸如“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..
    }
}

【问题讨论】:

  • 这就是onPostExecute 的用途
  • 您在 doInBackground() 方法中返回一个字符串值。您将在onPostExecute() 方法中获得响应字符串。所以使用result 字符串变量作为你的输出。

标签: java android android-asynctask httpresponse getresponse


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 2020-05-13
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多