使用 android 发出 HTTP 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3505930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make an HTTP request with android
提问by Mats Hofman
I have searched everywhere but I couldn't find my answer, is there a way to make an simple HTTP request? I want to request an PHP page / script on one of my website but I don't want to show the webpage.
我到处搜索,但找不到答案,有没有办法发出简单的 HTTP 请求?我想在我的网站之一上请求一个 PHP 页面/脚本,但我不想显示该网页。
If possible I even want to do it in the background (in an BroadcastReceiver)
如果可能的话,我什至想在后台进行(在 BroadcastReceiver 中)
回答by Konstantin Burov
UPDATE
更新
This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:
这是一个非常古老的答案。我绝对不会再推荐 Apache 的客户端了。而是使用:
Original Answer
原答案
First of all, request a permission to access network, add following to your manifest:
首先,请求访问网络的权限,将以下内容添加到您的清单中:
<uses-permission android:name="android.permission.INTERNET" />
Then the easiest way is to use Apache http client bundled with Android:
那么最简单的方法就是使用Android自带的Apache http客户端:
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());
}
If you want it to run on separate thread I'd recommend extending AsyncTask:
如果您希望它在单独的线程上运行,我建议扩展 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..
}
}
You then can make a request by:
然后,您可以通过以下方式提出请求:
new RequestTask().execute("http://stackoverflow.com");
回答by Elliott Hughes
unless you have an explicit reason to choose the Apache HttpClient, you should prefer java.net.URLConnection. you can find plenty of examples of how to use it on the web.
除非您有明确的理由选择 Apache HttpClient,否则您应该更喜欢 java.net.URLConnection。您可以在网络上找到大量有关如何使用它的示例。
we've also improved the Android documentation since your original post: http://developer.android.com/reference/java/net/HttpURLConnection.html
自您的原始帖子以来,我们还改进了 Android 文档:http: //developer.android.com/reference/java/net/HttpURLConnection.html
and we've talked about the trade-offs on the official blog: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
我们已经在官方博客上讨论了权衡:http: //android-developers.blogspot.com/2011/09/androids-http-clients.html
回答by kevinc
Note: The Apache HTTP Client bundled with Android is now deprecated in favor of HttpURLConnection. Please see the Android Developers Blogfor more details.
注意:与 Android 捆绑的 Apache HTTP 客户端现在已弃用,取而代之的是HttpURLConnection。有关更多详细信息,请参阅 Android 开发者博客。
Add <uses-permission android:name="android.permission.INTERNET" />
to your manifest.
添加<uses-permission android:name="android.permission.INTERNET" />
到您的清单。
You would then retrieve a web page like so:
然后你会像这样检索一个网页:
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();
}
I also suggest running it on a separate thread:
我还建议在单独的线程上运行它:
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..
}
}
See the documentationfor more information on response handling and POST requests.
有关响应处理和 POST 请求的更多信息,请参阅文档。
回答by Shao Wenbin
The most simple way is using the Android lib called Volley
最简单的方法是使用名为Volley的 Android 库
Volley offers the following benefits:
Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network. Debugging and tracing tools.
Volley 具有以下优势:
网络请求的自动调度。多个并发网络连接。具有标准 HTTP 缓存一致性的透明磁盘和内存响应缓存。支持请求优先级。取消请求 API。您可以取消单个请求,也可以设置要取消的请求块或范围。易于定制,例如,重试和退避。强排序可以轻松地使用从网络异步获取的数据正确填充您的 UI。调试和跟踪工具。
You can send a http/https request as simple as this:
您可以像这样简单地发送 http/https 请求:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.yourapi.com";
JsonObjectRequest request = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (null != response) {
try {
//handle your response
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
In this case, you needn't consider "running in the background" or "using cache" yourself as all of these has already been done by Volley.
在这种情况下,您不必自己考虑“在后台运行”或“使用缓存”,因为所有这些都已由 Volley 完成。
回答by Gabriel Gómez
private String getToServer(String service) throws IOException {
HttpGet httpget = new HttpGet(service);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return new DefaultHttpClient().execute(httpget, responseHandler);
}
Regards
问候
回答by electronix384128
Look at this awesome new library which is available via gradle :)
看看这个很棒的新库,它可以通过 gradle 获得:)
build.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'
构建.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'
Usage:
用法:
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();
回答by Deividson Calixto
I made this for a webservice to requerst on URL, using a Gson lib:
我使用 Gson 库为 Web 服务请求 URL 做了这个:
Client:
客户:
public EstabelecimentoList getListaEstabelecimentoPorPromocao(){
EstabelecimentoList estabelecimentoList = new EstabelecimentoList();
try{
URL url = new URL("http://" + Conexao.getSERVIDOR()+ "/cardapio.online/rest/recursos/busca_estabelecimento_promocao_android");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != 200) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
estabelecimentoList = new Gson().fromJson(br, EstabelecimentoList.class);
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return estabelecimentoList;
}
回答by fredley
With a thread:
用一个线程:
private class LoadingThread extends Thread {
Handler handler;
LoadingThread(Handler h) {
handler = h;
}
@Override
public void run() {
Message m = handler.obtainMessage();
try {
BufferedReader in =
new BufferedReader(new InputStreamReader(url.openStream()));
String page = "";
String inLine;
while ((inLine = in.readLine()) != null) {
page += inLine;
}
in.close();
Bundle b = new Bundle();
b.putString("result", page);
m.setData(b);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.sendMessage(m);
}
}
回答by Jarda Pavlí?ek
Use Volley as suggested above. Add following into build.gradle (Module: app)
按照上面的建议使用 Volley。将以下内容添加到 build.gradle(模块:app)
implementation 'com.android.volley:volley:1.1.1'
Add following into AndroidManifest.xml:
将以下内容添加到 AndroidManifest.xml 中:
<uses-permission android:name="android.permission.INTERNET" />
And add following to you Activity code:
并将以下内容添加到您的活动代码中:
public void httpCall(String url) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// enjoy your response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// enjoy your error status
}
});
queue.add(stringRequest);
}
It replaces http client and it is very simple.
它取代了http客户端,非常简单。
回答by Rahul Raina
This is the new code for HTTP Get/POST request in android. HTTPClient
is depricated and may not be available as it was in my case.
这是android中HTTP Get/POST请求的新代码。HTTPClient
已弃用,可能无法使用,就像我的情况一样。
Firstly add the two dependencies in build.gradle:
首先在build.gradle中添加两个依赖:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
Then write this code in ASyncTask
in doBackground
method.
然后ASyncTask
在doBackground
方法中编写此代码。
URL url = new URL("http://localhost:8080/web/get?key=value");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
InputStream it = new BufferedInputStream(urlConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
StringBuilder dta = new StringBuilder();
String chunks ;
while((chunks = buff.readLine()) != null)
{
dta.append(chunks);
}
}
else
{
//Handle else
}