在我的应用程序中使用HttpPost像这样解析json
`
HttpClient httpClient = new DefaultHttpClient();
HttpParams httpParameters = httpClient.getParams();
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpContext localContext = new BasicHttpContext();
String url="http://ashishva.comxa.com/getdata_shoplistl_f.php?route="+sroute+"&shop_type="+sshoptype;
HttpPost httpGet = new HttpPost(url);
HttpResponse response = httpClient.execute(httpGet, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()`
我的清单文件已正确设置为可访问互联网
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
我在我的浏览器中获取了json,但是只在我的Android手机和模拟器中获得了结果。为什么会这样呢?为什么有时候得到而不是后来。
虽然我没有得到任何数据,但我得到了例外
"java.net.UnknownHostException: Unable to resolve host "ashishva.comxa.com": No address associated with hostname"
答案 0 :(得分:1)
实际上我找到了解决方案。这一行
HttpPost httpGet = new HttpPost(url);
必须用HttpGet替换为
HttpGet httpGet = new HttpGet(url);
答案 1 :(得分:1)
我发现的最好的一个是Android开发人员培训,下面是链接
http://developer.android.com/training/basics/network-ops/connecting.html
连接并下载数据
// Given a URL, establishes an HttpUrlConnection and retrieves // the web page content as a InputStream, which it returns as a string. private String downloadUrl(String myurl) throws IOException { InputStream is = null; // Only display the first 500 characters of the retrieved // web page content. int len = 500; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); Log.d(DEBUG_TAG, "The response is: " + response); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = readIt(is, len); return contentAsString; // Makes sure that the InputStream is closed after the app is // finished using it. } finally { if (is != null) { is.close(); } } }
将InputStream转换为String
// Reads an InputStream and converts it to a String. public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { Reader reader = null; reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer); }