简体   繁体   English

接收来自HTTP请求的响应

[英]Receiving response from HTTP request

I am new to Java and I am trying to figure out how to receive a response from an HTTP request to a PHP page. 我是Java的新手,我想弄清楚如何从HTTP请求到PHP页面接收响应。

here is my main HTTP code: 这是我的主要HTTP代码:

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);
                out.close();
                responseString = out.toString();
            } 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..
    }
}

and this is what I am using to send the request: 这就是我用来发送请求的内容:

new RequestTask().execute("http://www.mywebsite.com/registercheck.php?first=" + first2 + "&last=" + last2 + "&dispname=" + display2 + "&email=" + email2 + "&password=" + password2 );

which is nestled in an on-click. 嵌套在单击中。 It works flawlessly, it adds the user to the table using the php file. 它可以完美地工作,它使用php文件将用户添加到表中。 Now how am I supposed to let my activity know that the entry was successful? 现在我应该如何让我的活动知道输入成功? Is there a way to read a response? 有没有办法阅读回应?

I tried searching but maybe I am looking for the wrong answers here, just a little confused. 我尝试搜索,但也许我在这里寻找错误的答案,只是有些困惑。 Thank you for any help or direction. 感谢您的帮助或指导。

You can use interface as a callback to the activity. 您可以将interface用作活动的回调。

Define a interface. 定义一个接口。 Let your activity implement the interface. 让您的活动实现该接口。 Use the interface as a cll back to the activity and return responseString . 将接口用作返回活动的cll并返回responseString

Example : 范例:

How do I return a boolean from AsyncTask? 如何从AsyncTask返回布尔值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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