[转载]Android_HttpClient_get请求post表单提交上传 – 子墨的Android开发之旅 – 博客频道 – CSDN.NET.
1.HttpRequestBase(HttpGet..)
HttpClient 支持多种访问网络的方式,包括GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS. 其对应子类为HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions.但在使用时多为HttpGet, HttpPost两种方式。
/** * 一个简单的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()等等
System.out.println(response.getProtocolVersion()); System.out.println(response.getStatusLine().getStatusCode()); System.out.println(response.getStatusLine().getReasonPhrase()); System.out.println(response.getStatusLine().toString());
输出结果为
/* HTTP/1.1 200 OK HTTP/1.1 200 OK */
//得到请求的响应数据
//方式一.
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方法,取得该输入流对应的数据
}
[/java]
3.ResponseHandler
/** * 通过ResponseHandler处理请求 */ private static void test() { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://www.baidu.com"); //自定义ResponseHandler对象 ResponseHandler myHandler = new ResponseHandler() { @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(); } }
5.GZIP压缩
对于文本数据,特别是json数据或者html网页数据,最好使用gzip进行压缩,理论上文本数据可以压缩为原来的1/3,效果很明显,压缩之后应该使用gzip流进行解压缩!
get.addHeader("Accept-Encoding", "gzip");//使用addHeader,否则没有效果 HttpResponse response = client.execute(get); int code = response.getStatusLine().getStatusCode(); Header header = response.getFirstHeader("Content-Encoding"); InputStream is = new BufferedInputStream(response.getEntity().getContent()); if (header != null && header.getValue().contains("gzip")) {//首先判断服务器是否支持gzip压缩 is = new GZIPInputStream(is); }
6.Post完成Form表单的提交
/** * 完成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 parameters = new ArrayList(); 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(); } }
7.Post完成文件的长传
/** * 通过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(); } }