Mat*_*man 347 android httpwebrequest androidhttpclient
我到处搜索但我找不到答案,有没有办法发出简单的HTTP请求?我想在我的某个网站上请求PHP页面/脚本,但我不想显示该网页.
如果可能的话我甚至想在后台(在BroadcastReceiver中)这样做
Kon*_*rov 470
这是一个非常古老的答案.我绝对不会再推荐Apache的客户了.而是使用:
首先,请求访问网络的权限,在清单中添加以下内容:
<uses-permission android:name="android.permission.INTERNET" />
Run Code Online (Sandbox Code Playgroud)
那么最简单的方法是使用与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());
}
Run Code Online (Sandbox Code Playgroud)
如果你想让它在单独的线程上运行,我建议扩展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..
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以通过以下方式提出请求:
new RequestTask().execute("http://stackoverflow.com");
Run Code Online (Sandbox Code Playgroud)
Ell*_*hes 65
除非您有明确的理由选择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
Kev*_*nly 44
注意:现在不推荐使用与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();
}
Run Code Online (Sandbox Code Playgroud)
我还建议在一个单独的线程上运行它:
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..
}
}
Run Code Online (Sandbox Code Playgroud)
有关响应处理和POST请求的详细信息,请参阅文档.
小智 12
最简单的方法是使用名为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);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您不必考虑自己"在后台运行"或"使用缓存",因为所有这些都已由Volley完成.
private String getToServer(String service) throws IOException {
HttpGet httpget = new HttpGet(service);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return new DefaultHttpClient().execute(httpget, responseHandler);
}
Run Code Online (Sandbox Code Playgroud)
问候
按照上面的建议使用 Volley。将以下内容添加到 build.gradle(模块:app)
implementation 'com.android.volley:volley:1.1.1'
Run Code Online (Sandbox Code Playgroud)
将以下内容添加到 AndroidManifest.xml 中:
<uses-permission android:name="android.permission.INTERNET" />
Run Code Online (Sandbox Code Playgroud)
并将以下内容添加到您的活动代码中:
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);
}
Run Code Online (Sandbox Code Playgroud)
它取代了http客户端,非常简单。
用线程:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
看看这个很棒的新库,可以通过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();
Run Code Online (Sandbox Code Playgroud)
https://github.com/erf/http-request
由于没有一个答案描述了使用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();
Run Code Online (Sandbox Code Playgroud)
这个库的明显优势在于,它将我们从一些低级细节中抽象出来,提供更友好和安全的方式与它们交互。语法也得到了简化,可以编写漂亮的代码。
归档时间: |
|
查看次数: |
409643 次 |
最近记录: |