我读到 HttpsURLConnection 在 2.3 之前是有问题的,我有关于它有问题的第一手经验。
我尝试过的替代方案是 HttpClient,但是它给我带来了问题,因为它返回给我:
<?xml version="1.0" encoding="iso-8859-1"?>
当我显然应该取回 JSON 时。
HttpsURLConnection 返回 JSON 正常,但在处理许多请求时有一些不一致的结果。 (通过返回 JSON,我的意思是响应应该包含 JSON)
知道为什么 HttpClient 返回一些 xml 标签而不是 JSON(应该返回什么)吗?
编辑 -- 代码
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParams = new ArrayList<NameValuePair>();
urlParams.add(new BasicNameValuePair("&platform=","Android"));
urlParams.add(new BasicNameValuePair("&action=","signin"));
urlParams.add(new BasicNameValuePair("&user",username));
urlParams.add(new BasicNameValuePair("&pass",password));
try {
post.setEntity(new UrlEncodedFormEntity(urlParams, HTTP.UTF_8));
HttpResponse resp = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
resp.getEntity().getContent()));
String line = "";
JSONArray ja = new JSONArray();
while ((line = rd.readLine()) != null) {
Log.i("------>", line);
ja = new JSONArray(line); //breaks here because it returns xml instead of JSON
}
rd.close();
return ja;
} catch (Exception e) {
e.printStackTrace();
return null;
}
这两个有更好的替代品吗?
最佳答案
这看起来像是服务器对错误页面的响应。您可能会收到 404 错误或许多其他 http 错误。这只是您从服务器返回的 html 文件的开头。您确定该 url 是有效的 url 并且会在不重定向的情况下接受来自移动设备的连接吗?
关于Android HttpsURLConnection 与 HttpClient,两者都有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8117573/