您的位置:首页 > 理论基础 > 计算机网络

android中的httpclient使用

2011-05-12 13:35 260 查看
用php搭建了个简单的服务器端,然后在android中使用httpclient来调用.

String httpurl="http://192.168.1.100/http/httptest.php?para=hello"; HttpGet httpGet=new HttpGet(httpurl); HttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); try{ HttpResponse httpResponse=httpclient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ String strResult=EntityUtils.toString(httpResponse.getEntity()); txtHello.setText(strResult); mWebView.loadUrl(httpurl); } else{ txtHello.setText("no response"); } }catch(IOException e){ e.printStackTrace(); }

刚开始发现在执行httpclient.execute的时候就没有了响应,程序没有继续执行,也没有报告错误,后来一查,需要加入相应的权限才可以:

<uses-permission android:name="android.permission.INTERNET" />

这样就可以正确的返回信息了.

接下来的问题是返回的信息中有中文,在android中显示为乱码,估计是服务器端的问题,于是在php中加入了编码:

header("Content-Type: text/html;charset=utf-8");

可以正常显示了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: