Android_HttpClient_get请求post表单提交上传

关于HttpUrlConnection用法

1.HttpRequestBase(HttpGet..)

HttpClient 支持多种访问网络的方式,包括GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS. 其对应子类为HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions.但在使用时多为HttpGet, HttpPost两种方式。

[java] 

/** 

 * 一个简单的get请求 

 */  

private static void get() {  

    // 1.得到HttpClient对象  

    HttpClient httpClient = new DefaultHttpClient();  

    // 2.实例化一个HttpGet对象  

    HttpGet httpGet = new HttpGet("http://www.baidu.com");  

    try {  

        // 3.httpClient执行httpGet请求  

        HttpResponse response = httpClient.execute(httpGet);  

        HttpEntity entity = response.getEntity();  

        if (entity != null) { // 如果有数据表示请求成功  

            System.out.println(EntityUtils.toString(entity, "utf-8"));  

        } else {  

            System.out.println("连接失败!");  

        }  

    } catch (Exception e) {  

        e.printStackTrace();  

    } finally {  

        // 4.释放资源(Shuts down this connection manager and releases allocated  

        // resources)  

        httpClient.getConnectionManager().shutdown();  

    }  

}  

2.HttpResponse

通过得到HttpResponse对象,可以得到相关访问网络的信息,比如getEntity() getStatusLine()等等

[java]  

System.out.println(response.getProtocolVersion());  

System.out.println(response.getStatusLine().getStatusCode());  

System.out.println(response.getStatusLine().getReasonPhrase());  

System.out.println(response.getStatusLine().toString());  

输出结果为

[java]  

/* 

HTTP/1.1 

200 

OK 

HTTP/1.1 200 OK 

*/  

[java] 

//得到请求的响应数据  

//方式一.  

HttpEntity entity = response.getEntity();  

if (entity != null) { // 如果有数据表示请求成功  

    System.out.println(EntityUtils.toString(entity, "utf-8"));  

} else {  

    System.out.println("连接失败!");  

}  

//方式二.  

if(response.getStatusLine().getStatusCode() == 200){  

    HttpEntity myEntity = response.getEntity();  

    BufferedInputStream in = new BufferedInputStream(myEntity.getContent());  

    byte[] bytes = read(in);//通过自定义的read方法,取得该输入流对应的数据  

}  

3.ResponseHandler

[java]  

/** 

 * 通过ResponseHandler处理请求 

 */  

private static void test() {  

    HttpClient httpClient = new DefaultHttpClient();  

    HttpGet httpGet = new HttpGet("http://www.baidu.com");  

      

    //自定义ResponseHandler对象  

    ResponseHandler<String> myHandler = new ResponseHandler<String>() {  

        @Override  

        public String handleResponse(HttpResponse response)  

                throws ClientProtocolException, IOException {  

            HttpEntity entity = response.getEntity();  

            String result = "连接失败!";  

            if (entity != null) { // 如果有数据表示请求成功  

                result = EntityUtils.toString(entity, "utf-8");  

            }  

            return result;  

        }  

    };  

    try {  

        String result = httpClient.execute(httpGet, myHandler);//接收该myHandler对象  

        System.out.println(result);  

    } catch (Exception e) {  

        e.printStackTrace();  

    } finally {  

    // 释放资源(Shuts down this connection manager and releases allocated resources)  

        httpClient.getConnectionManager().shutdown();  

    }  

}  

4.Post完成Form表单的提交

[java] 

/** 

 * 完成form表单的提交 

 */  

private static void post() {  

    HttpClient httpClient = new DefaultHttpClient();  

    HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/My/upload");  

  

    try {  

        // 为httpPost设置HttpEntity对象  

        List<NameValuePair> parameters = new ArrayList<NameValuePair>();  

        parameters.add(new BasicNameValuePair("username", "zhangsan"));  

        parameters.add(new BasicNameValuePair("password", "123321"));  

        HttpEntity entity = new UrlEncodedFormEntity(parameters);  

        httpPost.setEntity(entity);  

        // httpClient执行httpPost表单提交  

        HttpResponse response = httpClient.execute(httpPost);  

        // 得到服务器响应实体对象  

        HttpEntity responseEntity = response.getEntity();  

        if (responseEntity != null) {  

            System.out.println(EntityUtils  

                    .toString(responseEntity, "utf-8"));  

            System.out.println("表单上传成功!");  

        } else {  

            System.out.println("服务器无响应!");  

        }  

    } catch (Exception e) {  

        e.printStackTrace();  

    } finally {  

        // 释放资源  

        httpClient.getConnectionManager().shutdown();  

    }  

}  

5.Post完成文件的长传

[java] 

/** 

 * 通过post完成文件的上传 

 */  

private static void postFile() {  

    HttpClient httpClient = new DefaultHttpClient();  

    HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/My/upload");  

    try {  

        // 需要上传的文件  

        String root = "D:/api/";  

        String fileName = "JDK6.0 中文文档.CHM";  

        File uploadFile = new File(root+fileName);  

        //定义FileEntity对象  

        HttpEntity entity = new FileEntity(uploadFile);  

        //为httpPost设置头信息  

        httpPost.setHeader("filename", URLEncoder.encode(fileName,"utf-8"));//服务器可以读取到该文件名  

        httpPost.setHeader("Content-Length", String.valueOf(entity.getContentLength()));//设置传输长度  

        httpPost.setEntity(entity); //设置实体对象  

          

        // httpClient执行httpPost提交  

        HttpResponse response = httpClient.execute(httpPost);  

        // 得到服务器响应实体对象  

        HttpEntity responseEntity = response.getEntity();  

        if (responseEntity != null) {  

            System.out.println(EntityUtils.toString(responseEntity, "utf-8"));  

            System.out.println("文件 "+fileName+"上传成功!");  

        } else {  

            System.out.println("服务器无响应!");  

        }  

    } catch (Exception e) {  

        e.printStackTrace();  

    } finally {  

        // 释放资源  

        httpClient.getConnectionManager().shutdown();  

    }  

}  


转载地址:http://www.2cto.com/kf/201310/248095.html

你可能感兴趣的:(Android_HttpClient_get请求post表单提交上传)