【发布时间】:2015-01-19 19:42:28
【问题描述】:
我正在使用 Konstantin Burov 在 Stackoverflow 帖子 (Make an HTTP request with android) 上演示的以下指南:
首先,请求访问网络的权限,将以下内容添加到您的清单中:
<uses-permission android:name="android.permission.INTERNET" />
那么最简单的方法就是使用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);
out.close();
String responseString = out.toString();
//..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);
out.close();
responseString = out.toString();
} 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");
我的问题是我现在如何在字符串中发布实际结果?我得到的只是我执行 new RequestTask().execute(url).toString(); 时的地址;
【问题讨论】:
标签: java android json android-asynctask get