我的手机APP以文本模式完美下载内容。下面是执行此操作的代码。我将其称为Communicator类和exectueHttpGet:
URL_Data = new Communicator().executeHttpGet("Some URL");
public class Communicator { public String executeHttpGet(String URL) throws Exception { BufferedReader in = null; try { HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android"); HttpGet request = new HttpGet(); request.setHeader("Content-Type", "text/plain; charset=utf-8"); request.setURI(new URI(URL)); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String page = sb.toString(); //System.out.println(page); return page; } finally { if (in != null) { try { in.close(); } catch (IOException e) { Log.d("BBB", e.toString()); } } } } }
我要讲的是(URL的源代码):
[{"id_country":"3","country":"AAA"},{"id_country":"8","country":"BBB"}, {"id_country":"66","country":"CCC"},{"id_country":"14","country":"DDD"}, {"id_country":"16","country":"EEE"},{"id_country":"19","country":"FFF"}, {"id_country":"24","country":"GGG"},{"id_country":"33","country":"HHH"}, {"id_country":"39","country":"III"},{"id_country":"44","country":"JJJ"}, {"id_country":"45","country":"KKK"},{"id_country":"51","country":"LLL"}, {"id_country":"54","country":"MMM"},{"id_country":"55","country":"NNN"}, {"id_country":"57","country":"OOO"},{"id_country":"58","country":"PPP"}, {"id_country":"63","country":"RRR"},{"id_country":"65","country":"SSS"}]
该响应是一个字符串。在服务器上,它作为JSON对象输出(与PHP一起),现在在我的Android PHP中,我想将此字符串转换为JSON。这可能吗?
您收到的是从InputStream附加到a StringBuffer并String最终转换为的一系列字符-因此,结果是String可以的:)
InputStream
StringBuffer
String
您想要的是通过org.json.*类似这样的类对该字符串进行后处理
org.json.*
String page = new Communicator().executeHttpGet("Some URL"); JSONObject jsonObject = new JSONObject(page);
然后继续jsonObject。由于您收到的数据是一个数组,因此您可以说
jsonObject
String page = new Communicator().executeHttpGet("Some URL"); JSONArray jsonArray = new JSONArray(page); for (int i = 0 ; i < jsonArray.length(); i++ ) { JSONObject entry = jsonArray.get(i); // now get the data from each entry }