android中的httpclient使用

用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"); 

可以正常显示了. 

原文地址:https://www.cnblogs.com/GarfieldTom/p/2044275.html