制作了Android的HTTP请求 [英] Make an HTTP request with android
问题描述
我到处找,但我无法找到我的答案,有没有一种方法,使一个简单的HTTP请求?我想在我的网站之一请求一个PHP页面/脚本,但我不想显示该网页。
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.
如果可能,我甚至想这样做的背景(在BroadcastReceiver的)
If possible I even want to do it in the background (in an BroadcastReceiver)
推荐答案
首先,请访问网络,添加权限下你的清单:
First of all, request a permission to access network, add following to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
那么最简单的方法是使用捆绑与Android的Apache HTTP客户端:
Then the easiest way is to use Apache http client bundled with 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的:
If you want it to run on separate thread I'd recommend extending 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");
这篇关于制作了Android的HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!