在Android客户端上发送http请求, 之前写过一篇关于使用Socket连接来模拟发送http请求的例子,那篇文章的url地址是:http://blog.foreverlove.us/2077.html

在Android中也有http的类, 那么可以直接使用这种类来发送请求, 在网络上淘了一些数据后, 总结得到的结果

一.Post请求的函数

// 通过POST将本地数据发送给服务器,string参数表
    public static String sendDataByPost(String url, List<NameValuePair> datas) {
        org.apache.http.client.HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        HttpResponse resp = null;
        String result = "";
        // post data
        try {
            post.setEntity(new UrlEncodedFormEntity(datas, HTTP.UTF_8));
            resp = client.execute(post);
            result = EntityUtils.toString(resp.getEntity());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

二,get请求的函数

/**
     *Get请求
     */
    public void doGet(String url){
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,30000); 
        HttpConnectionParams.setSoTimeout(httpParams, 30000); 
           
        HttpClient httpClient = new DefaultHttpClient(httpParams); 
        // GET
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
                Log.i("GET", "Bad Request!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

三, post 方法的使用的具体实例

List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
                nameValuePair.add(new BasicNameValuePair("username", "zxg"));
                nameValuePair.add(new BasicNameValuePair("password", "11"));
                nameValuePair.add(new BasicNameValuePair("scheme", "http"));
               
                String result= sendDataByPost("http://132.132.254.97/servlet/LoginServlet", nameValuePair);
                Log.i(TAG,result);
               
                if(result.equals("{success:true}")){
                   
                    //登陆成功..
                    mHandler.obtainMessage(1).sendToTarget();
                }