[android] 01_HttpClient中的HttpGet和HttpPost请求方式

Android 4.0

HttpClient中的HttpGet和HttpPost请求方式 

HttpClientapache 发布,模拟一个浏览器 
步骤:
1.打开浏览器
HttpClient client = new DefaultHttpClient()
2.输入一些内容
HttpGet
3.敲回车
client.execute(path);
1、HttpGe
    /**
     * 1、使用HttpClient——GET方式进行登录
     * 
     * @throws IOException
     */
    public static String loginByGet(String username, String password)throws IOException {
        
        System.out.println("以GET方式提交。。。");
        // 1、打开一个浏览器
        HttpClient client = new DefaultHttpClient();

        String path = "http://192.168.221.221:8080/web/LoginServlet?username="
                + username + "&password" + password;
        // 2、输入url地址
        HttpGet httpGet = new HttpGet(path);

        // 3、敲回车
        HttpResponse response = client.execute(httpGet);

        int code = response.getStatusLine().getStatusCode();
        if (code == 200) {
            // 数据实体
            HttpEntity entity = response.getEntity();
            InputStream in = entity.getContent();
            String text = StreamUtils.readStream(in);
            return text;
        }
        return null;
    }
2、HttpPost 
        /**
     * 2、使用HttpClient——POST方式登录
     * 
     * @param username
     * @param password
     * @return
     * @throws IOException
     */
    public static String loginByPost(String username, String password)
            throws IOException {
        System.out.println("以POST方式登录。。。");

        String path = "http://192.168.221.221:8080/web/LoginServlet";
        // 1、打开一个浏览器

        HttpClient client = new DefaultHttpClient();
        // 2、输入url地址

        HttpPost httpPost = new HttpPost(path);

        // 3、设置请求内容
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("username", username));
        parameters.add(new BasicNameValuePair("password", password));
        HttpEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
        // 对请求参数进行编码:encoding the name/value pairs be encoded with
        httpPost.setEntity(entity);
        
        // 4、敲回车
        HttpResponse response = client.execute(httpPost);
        int code = response.getStatusLine().getStatusCode(); // 服务器状态码
        if (code == 200) {
            InputStream in = response.getEntity().getContent();
            String text = StreamUtils.readStream(in);
            return text;
        }
        return null;
    }