我到处都找过了,但我找不到我的答案,有没有一种方法可以做一个简单的HTTP请求?我想在我的一个网站上请求一个PHP页面/脚本,但我不想显示网页。

如果可能的话,我甚至想在后台(在一个BroadcastReceiver)做它


当前回答

更新

这是一个非常古老的答案。我绝对不会再推荐Apache的客户端了。你可以用任意一种:

改造 OkHttp 截击 HttpUrlConnection

原来的答案

首先,申请访问网络的权限,在您的清单中添加以下内容:

<uses-permission android:name="android.permission.INTERNET" />

那么最简单的方法是使用Apache http客户端与Android捆绑:

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(URL));
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        String responseString = out.toString();
        out.close();
        //..more logic
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }

如果你想让它在单独的线程上运行,我建议扩展AsyncTask:

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

然后,你可以通过以下方式提出请求:

   new RequestTask().execute("http://stackoverflow.com");

其他回答

看看这个很棒的新库,它可以通过gradle获得:)

构建。Gradle:编译'com.apptakk.http_request:http-request:0.1.2'

用法:

new HttpRequestTask(
    new HttpRequest("http://httpbin.org/post", HttpRequest.POST, "{ \"some\": \"data\" }"),
    new HttpRequest.Handler() {
      @Override
      public void response(HttpResponse response) {
        if (response.code == 200) {
          Log.d(this.getClass().toString(), "Request successful!");
        } else {
          Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
        }
      }
    }).execute();

https://github.com/erf/http-request

除非你有明确的理由选择Apache HttpClient,否则你应该选择java.net.URLConnection。你可以在网上找到很多如何使用它的例子。

我们也改进了Android文档,因为你原来的帖子:http://developer.android.com/reference/java/net/HttpURLConnection.html

我们已经在官方博客http://android-developers.blogspot.com/2011/09/androids-http-clients.html上讨论了这些权衡

更新

这是一个非常古老的答案。我绝对不会再推荐Apache的客户端了。你可以用任意一种:

改造 OkHttp 截击 HttpUrlConnection

原来的答案

首先,申请访问网络的权限,在您的清单中添加以下内容:

<uses-permission android:name="android.permission.INTERNET" />

那么最简单的方法是使用Apache http客户端与Android捆绑:

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(URL));
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        String responseString = out.toString();
        out.close();
        //..more logic
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }

如果你想让它在单独的线程上运行,我建议扩展AsyncTask:

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

然后,你可以通过以下方式提出请求:

   new RequestTask().execute("http://stackoverflow.com");

注意:与Android捆绑的Apache HTTP客户端现在已弃用,转而支持HttpURLConnection。请参阅Android开发者博客了解更多细节。

添加<uses-permission android:name="android.permission. "INTERNET" />到您的舱单。

然后你会像这样检索一个网页:

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
}
finally {
     urlConnection.disconnect();
}

我还建议在一个单独的线程上运行它:

class RequestTask extends AsyncTask<String, String, String>{

@Override
protected String doInBackground(String... uri) {
    String responseString = null;
    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK){
            // Do normal input or output stream reading
        }
        else {
            response = "FAILED"; // See documentation for more info on response handling
        }
    } 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..
}
}

有关响应处理和POST请求的更多信息,请参阅文档。

private String getToServer(String service) throws IOException {
    HttpGet httpget = new HttpGet(service);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    return new DefaultHttpClient().execute(httpget, responseHandler);

}

问候