0

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

1 に答える 1

0

リクエスト URL ( http://192.168.1.1/key_off ) で 404 エラー コードが表示されていることを確認してください。Web で URL を起動してください。

于 2016-07-19T13:10:08.873 に答える