我愿意从http请求中读取一个简单的json文件。 这是我试用的URL:
http://tccdahora.servehttp.com/teste.php
所以,我有一种方法可以将URL转换为JSON,但它不起作用,我尝试了很多不同的方法或者在帖子上获得了一个标题,但没有成功。
这是方法:
public static JSONArray getPostJSONObject(String url) throws Throwable {
// faz o POST na pagina php e obtem o inputstream de resposta
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url); // "http://tccdahora.servehttp.com/teste.php"
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("host", url);
//httppost.setHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
// transforma o que o php printar em uma strigzona
JSONArray jArray;
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String result = sb.toString();
Log.e("", result);
// transformando em uma array de objetos JSON
jArray = new JSONArray(result);
return jArray;
}
我有什么问题吗?我收到错误的请求错误,帖子中的字符串返回一个HTML CODE通知错误,而不是浏览器显示的json。
非常感谢您的关注!
答案 0 :(得分:0)
删除以下行:
httppost.setHeader("host", url);