我正在尝试使用此代码从Web服务器获取inputStrem
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
InputStream stream = conn.getInputStream();
return stream;
}
当我尝试使用此输入流来获取String时,我错过了beggining和end,所以它似乎正在削减一些东西。 但是使用DefaultHttpClient,HttpGet和HttpResponse结果是可以的。
private String downloadPHP(String urlString){
String st = null;// aqui el XML descargado
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
st = StringUtils.inputStreamToString(content);
}
catch (Exception e) {
//Log.i(Constants.DEBUG_TAG, e.getMessage());
}
return st;
}
由于Google推荐使用HttpUrlConnection,有什么想法可以解决这个问题吗?
这是从inoutstream获取字符串的方法
public static String inputStreamToString(final InputStream stream) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
答案 0 :(得分:2)
我们再次检查了代码,也检查了服务器端,最后是服务器发送数据的问题。服务器不以正确的格式发送数据。我们已经改变了PHP代码,现在使用HttpUrlCOnnection,因为它在原始问题中描述一切正常。 在服务器端,信息没有获得xml格式,我们已经使用PHP DOM解决了它
答案 1 :(得分:0)
尝试以下代码从输入流中读取。
byte[] buf;
ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
int read = inputStream.read();
while (read != -1) {
baos.write((byte) read);
read = inputStream.read();
}
baos.flush();
buf = baos.toByteArray();