小项目需要读取数据库,刚好手头有服务器,处于某些考虑,还是想远程读数据,所遇异常
Logcat异常:SingleClientConnManager(411): Invalid use of SingleClientConnManager: connection still allocated. Make sure to release the connection before allocating another one. request time failed: java.net.SocketException: Address family not supported by protocol
基本思路就是,通过一个按钮监听事件,利用HttpClient来实现交互。<关于更多HttpClient点击此处:>
上核心代码:
PHP代码:
<?php
$array=array('title'=>'name','value'=>'doooger');
json_encode($array);
?>
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //TextView homeContext=new TextView(this); setContentView(R.layout.tel); Button btn = (Button)findViewById(R.id.getPhpJson); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub EditText edit = (EditText)findViewById(R.id.typeId); Log.i(Tag, "eeeeeeee"); String url = "http://www.test.com:80/an/index.php?type=1"; getServerJsonDataWithNoType(url,edit); } }); }-----------------------------------------------------------------------------------------------------------------public void getServerJsonDataWithNoType(String url,EditText editText) { int res = 0; HttpClient client = new DefaultHttpClient(); StringBuilder str = new StringBuilder(); HttpGet httpGet = new HttpGet(url); try { HttpResponse httpRes = client.execute(httpGet); httpRes = client.execute(httpGet); res = httpRes.getStatusLine().getStatusCode(); if(res == 200) { BufferedReader buffer = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent())); for(String s = buffer.readLine(); s != null ; s = buffer.readLine()) { str.append(s); } //String out = EntityUtils.toString(httpRes.getEntity().getContent(), "UTF-8"); //StringBuilder sb = new StringBuilder() Log.i(Tag,str.toString()); try { //JSONObject json = new JSONObject(str.toString()).getJSONObject("content"); JSONObject json = new JSONObject(str.toString()); String title = json.getString("title"); Log.i(Tag,title); int id = json.getInt("id"); String value = json.getString("value"); Log.i(Tag,value); editText.setText("Title:" + title + " ID:" + id + " Value:" + value); } catch(JSONException e) { Log.i(Tag, e.getLocalizedMessage()); //buffer.close(); e.printStackTrace(); } } else { Log.i(Tag, "HttpGet Error"); } } catch(Exception e) { Log.i(Tag, "Exception"); } }
解决办法:
url没拼对,用的是本地的虚拟服务器,android的本地ip对应的是10.0.2.2,所以url应该如下拼写:<貌似只能用IIS的默认网站进行交互,如果谁知道怎么用hosts拦截DNS解析用域名访问的方法欢迎留言> String url = ""; 这样,就没有问题了! PS:IIS加载PHP模块需要两步: 1、加载php5isapi.dll 2、iis->对应网站->主目录->配置->映射加载对应的php5isapi.dll
------------------------------------------------------------------------------------------------------------------------------