我的手机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中的一系列字符,你追加到StringBuffer并在最后转换为String – 所以String的结果是ok