我遇到Android问题:
我必须能够从生成它们的URL中读取内容,然后将它们放入一个数组中拆分字符串read。我使用了不同的方法,但我无法读取该字符串。我该怎么办?
这是我现在使用的功能(继续显示字符串“nn va”):
private void vaia () { // funzione vaia *******************************************************
try {
HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet(URL); // Set the action you want to do
HttpResponse response = httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) // Read line by line
sb.append(line + "\n");
String resString = sb.toString(); // Result is here
Log.i("string letta", resString);
is.close(); // Close the stream
}
catch (Exception e) {
Log.i("Risultato eccezione","nn va");
//e.printStackTrace();
}
}
此点的URL:http://www.innovacem.com/public/glace/leggiFoto.php(应写“vuoto”)
谢谢:)
答案 0 :(得分:1)
通过此方法尝试。
public static String getResponseFromUrl(String url) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}
感谢。
答案 1 :(得分:1)
使用异步任务:
private class ReadTask extends AsyncTask<String, Integer, String>
{
@Override
protected String doInBackground(String... params)
{
getResponseFromUrl(params[0]);
return "success";
}
}
要调用它,请使用:
new ReadTask().execute(<your url>);