我已经到处搜寻,但找不到我的答案,有没有一种方法可以发起简单的HTTP请求? 我想要请求我网站上的一个PHP页面/脚本,但我不想显示网页。
如果可能,我甚至想在后台执行(在广播接收器中)。
我已经到处搜寻,但找不到我的答案,有没有一种方法可以发起简单的HTTP请求? 我想要请求我网站上的一个PHP页面/脚本,但我不想显示网页。
如果可能,我甚至想在后台执行(在广播接收器中)。
这是一个非常老的答案。我绝对不再推荐使用Apache的客户端。相反,建议使用以下任一:
首先,请求访问网络的权限,并将以下内容添加到您的清单中:
<uses-permission android:name="android.permission.INTERNET" />
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());
}
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");
如果没有明确选择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
注意:Android自带的Apache HTTP Client现已过时,建议使用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请求的更多信息。
readStream
甚至没有定义。 - Eugene K最简单的方法是使用名为Volley的Android库。
Volley提供以下好处:
自动调度网络请求。 多个并发网络连接。透明磁盘和内存响应缓存,并支持标准HTTP缓存一致性。支持请求优先级。取消请求API。您可以取消单个请求,也可以设置要取消的请求块或范围。易于自定义,例如,用于重试和退避。强大的排序使得从网络异步获取的数据正确地填充UI变得容易。调试和跟踪工具。
您可以像这样简单地发送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);
在这种情况下,您不需要考虑“在后台运行”或“使用缓存”,因为Volley已经完成了所有这些工作。按照上述建议使用 Volley。将以下内容添加到 build.gradle(Module:app)中。
implementation 'com.android.volley:volley:1.1.1'
将以下内容添加到AndroidManifest.xml中:<uses-permission android:name="android.permission.INTERNET" />
并将以下内容添加到您的Activity代码中:
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);
}
它替代了HTTP客户端,而且非常简单。
queue.add(...
之后,您的代码将继续执行。 - Jarda Pavlíčekqueue.add()
之后组织一个繁忙循环之外,还有什么方法吗? - Violet Giraffe由于没有任何答案描述如何使用OkHttp进行请求,而OkHttp是当今Android和Java中非常流行的http客户端,因此我将提供一个简单的示例:
//get an instance of the client
OkHttpClient client = new OkHttpClient();
//add parameters
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://www.example.com").newBuilder();
urlBuilder.addQueryParameter("query", "stack-overflow");
String url = urlBuilder.build().toString();
//build the request
Request request = new Request.Builder().url(url).build();
//execute
Response response = client.newCall(request).execute();
private String getToServer(String service) throws IOException {
HttpGet httpget = new HttpGet(service);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return new DefaultHttpClient().execute(httpget, responseHandler);
}
问候
使用线程:
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);
}
}
看看这个很棒的新库,可以通过gradle获取 :)
build.gradle: compile '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();
我为一个使用Gson库请求URL的Web服务制作了这个:
客户端:
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;
}