HttpClient网络连接代码

来源:互联网 发布:同程网络 编辑:程序博客网 时间:2024/04/19 10:52
Android网络连接代码如下:

public class NetworkUtils {
    private static final String TAG ="NetworkUtils";
    private static final String CHARSET=HTTP.UTF_8;
    private static HttpClient singleHttpClient;
    
    private NetworkUtils(){
        
    }
    
    /**
     * 保证HttpClient的单例使用 
     */
    public static synchronized HttpClient getHttpClient(){
        if(null==singleHttpClient){
            HttpParams params = new BasicHttpParams();
            /* 设置一些基本参数 */
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, CHARSET);
            HttpProtocolParams.setUseExpectContinue(params, true);
            String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
            HttpProtocolParams.setUserAgent(params,userAgent);
            
            /* 超时设置 */
            /* 从连接池中取连接的超时时间 */
            ConnManagerParams.setTimeout(params, 1000);
            /* 连接超时 */
            HttpConnectionParams.setConnectionTimeout(params, 2000);
            /* 请求超时 */
            HttpConnectionParams.setSoTimeout(params, 4000);


            /* 设置我们的HttpClient支持HTTP和HTTPS两种模式 */
            SchemeRegistry schReg = new SchemeRegistry();
            schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));


            /* 使用线程安全的连接管理来创建HttpClient */
            ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
            singleHttpClient = new DefaultHttpClient(conMgr, params);
        }
        return singleHttpClient;
    }
    

/****************************************************************/

    public static String doPost(String url, List<NameValuePair> params) {
        String strResult = "doPostError";


        String temp = url.toLowerCase();
        if (!temp.startsWith("http://") && !temp.startsWith("https://")) {
            url = "http://" + url;
        }


        try {
            // 参数
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, CHARSET);


            // 创建POST请求
            HttpPost request = new HttpPost(url);
            request.setEntity(entity);
            // 发送请求
            HttpClient client = getHttpClient();
            HttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                strResult = "Error Response: " + response.getStatusLine().toString();
            }else{
                strResult = EntityUtils.toString(response.getEntity());
            }
        } catch (UnsupportedEncodingException e) {
            strResult = e.getMessage().toString();
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            strResult = e.getMessage().toString();
            e.printStackTrace();
        } catch (IOException e) {
            if(null!=e){
                if(null!=e.getMessage()){
                    strResult = e.getMessage().toString();
                    e.printStackTrace();
                }else{
                    strResult = "HttpClient excute Error,"+e;
                }
            }
            if(null==e){
                strResult = "HttpClient excute Error, connection was aborted";
            }
            
            if(strResult.toLowerCase().contains("error") || strResult.toLowerCase().contains("timed out") 
                    ||strResult.toLowerCase().contains("refuse")){
                strResult="connection error,please check whether server is running";
            }
            
        } catch (Exception e) {
            strResult = e.getMessage().toString();
            e.printStackTrace();
        }


        LogUtils.getInstance().d(strResult);
        return strResult;
    }
/****************************************************************/

调用函数时,注意增加判断结果

if(result.toString().contains("error")){
                        CommonTools.toast(activity, "连接服务器失败,请检查网络或服务器是否正常");
                        return;
 }

 /****************************************************************/   

 

  

    
    public static String doGet(String url) {
        String strResult = "doGetError";
        
        String temp = url.toLowerCase();
        if (!temp.startsWith("http://") && !temp.startsWith("https://")) {
            url = "http://" + url;
        }
        
        try {
            // 发送请求
            HttpClient client = getHttpClient();
            
            // 创建Get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                strResult = "Error Response: " + response.getStatusLine().toString();
            }
            HttpEntity resEntity = response.getEntity();
            return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET);
        } catch (UnsupportedEncodingException e) {
            strResult = e.getMessage().toString();
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            strResult = e.getMessage().toString();
            e.printStackTrace();
        } catch (IOException e) {
            strResult = e.getMessage().toString();
            e.printStackTrace();
        } catch (Exception e) {
            strResult = e.getMessage().toString();
            e.printStackTrace();
        }
        
//      Log.w(TAG, strResult);
        LogUtils.getInstance().d(strResult);
        return strResult;
    }


    /**
     * 读取数据
     */
    private static String convertStreamToString(InputStream is) 
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}


引用代码

    @Override
    public Object doInBackground(int loadCode) {
        // TODO Auto-generated method stub
    
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("xxxx",xxxx));
        params.add(new BasicNameValuePair("xxxxx", xxxxx));
        params.add(new BasicNameValuePair("xxxxx", xxxxx));
        
        return NetworkUtils.doPost(Constant.HOSTLOGIN, params);
    }


    @Override
    public void doInUI(Object result, int loadCode) {
        // TODO Auto-generated method stub
        try {
            JSONObject json = new JSONObject(result.toString());
            if ("0000".equals(json.getString("respCode"))) {
                Constant.isLogin=true;
                String data=json.getString("respData");
                String dataArray[]= data.split(",");
                for(int i=0;i<dataArray.length;i++){
                    String val[]=dataArray[i].split(":");
                    if(val[0].contains("realName")){
                        Constant.realName=val[1].replace("\"", "").trim();
                    }
                }
                
                
                finish();
            } else {
                Animation shake = AnimationUtils.loadAnimation(LoginActivity.this, R.anim.shake);
                account.startAnimation(shake);
                Log.e("用户登录数据解析失败");
                toast(this, json.getString("respMsg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("用户登录数据解析失败");
            toast(this, "用户登录数据解析失败");
        }
    }

本文转载自:http://www.cnblogs.com/codingmyworld/archive/2011/08/17/2141706.html



0 0
原创粉丝点击