private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
// textView.setText(Html.fromHtml(result));
Log.i("NNNNNNNNNNNNNN", ""+Html.fromHtml(result));
}
}
响应:
{
"error": 0,
"message": "Success",
"url": "http://demo.ftheline.com/restaurant/soma-eats/thank-you/710"
}
如何从给定网址获取String
的数据?我试过上面的代码并得到HTML
错误响应?请帮忙
答案 0 :(得分:0)
您可以使用以下方式将其归档。
我在我的应用程序中使用以下方式获取weburi的响应。
看看:
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
String responseString = null;
DefaultHttpClient client = new DefaultHttpClient();
@Override
protected String doInBackground(String... urls) {
String response = "";
try {
HttpGet httpGet = new HttpGet(url);
HttpResponse execute = client.execute(httpGet);
StatusLine statusLine = execute.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
HttpEntity httpEntity = response.getEntity();
responseString = EntityUtils.toString(httpEntity);
}else {
//Closes the connection.
execute.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
e.printStackTrace();
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
if(result!= null){
// textView.setText(Html.fromHtml(result));
Log.i("NNNNNNNNNNNNNN", ""+Html.fromHtml(result));
}
}
}