URL url = new URL(host);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
System.out.print(code);
if (code==200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
String content = in.toString();
System.out.print(content);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(new InputStreamReader(in, "UTF-8"));
result = (String) jsonObject.get("name");
System.out.print(jsonObject);
}
in.close();
}
当我拥有诸如http://www.example.com/json.txt
之类的主机字符串时,一切正常,但是当我拥有诸如www.example.com/index.php?data=data&data2=data2
之类的主机字符串时,出现以下错误:
W / System.err:位置0处的意外字符()。 I / System.out:200java.io.BufferedInputStream@8bc189fpp = [0,700,250,700]
我在浏览器中输出的PHP看起来不错,当我将其复制到json.txt
时,它也可以正常工作。
我尝试玩urlConnection POST,GET和RAW时没有运气。
有什么想法吗?
答案 0 :(得分:0)
问题可能是php json中的BOM。
我这样做:
URL url = new URL(host);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
System.out.print(code);
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StringWriter writer = new StringWriter();
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
result = result.substring(1);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(result);
result=(String) jsonObject.get("name");
System.out.print(jsonObject);
}
in.close();
}
它有效。