</pre>一.get和post请求方法的封装<p></p><p><span style="white-space:pre"></span>首先是post方法:</p><p></p><pre code_snippet_id="601727" snippet_file_name="blog_20150210_2_1231912" name="code" class="java">/**
* 进行post请求
*
* @param client HttpClient实例
* @param url 链接地址
* @param list 需要提交的数据的List
* @return 请求后返回的信息
*/
public static String doPost(DefaultHttpClient client, String url,
List<NameValuePair> list) {
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, HTTP.UTF_8); // 设置编码
HttpPost post = new HttpPost(url.trim()); // 进行post请求
post.setEntity(entity); // 加入请求头
Log.d(TESTHTTPCLIENT, "请求头内容:" + post.getAllHeaders().toString() + "::"
+ post.getHeaders("email").toString() + "::" + post.getEntity().getContent().toString());
HttpResponse response = client.execute(post); // 执行post请求
int codeReturn = response.getStatusLine().getStatusCode(); // 获取返回码
if (codeReturn == HttpStatus.SC_OK) {
Log.d(TESTHTTPCLIENT, "请求成功");
HttpEntity httpEntity = response.getEntity();
return httpEntity == null ? null : EntityUtils.toString(httpEntity);
} else {
Log.d(TESTHTTPCLIENT, "请求失败");
return null;
}
} catch (UnsupportedEncodingException e) {
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
然后是get方法:
/**
* 执行GET请求
*
* @param client HttpClient实例
* @param url 请求的链接
* @param map 需要提交的参数,放在map中
* @return 获取xml信息
*/
public static String doGet(DefaultHttpClient client, String url, Map<String, String> map) {
StringBuilder sb = null;
if (map != null) {
// url重新构造
sb = new StringBuilder(url);
sb.append('?');
// ?page=1&tags="计算机"(全部则为all)
for (Map.Entry<String, String> entry : map.entrySet()) {
try {
sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), "UTF-8"))
.append('&');
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
sb.deleteCharAt(sb.length() - 1);
Log.d("TestApp", "构造的URL为:" + sb.toString());
} else {
sb = new StringBuilder(url);
}
// 开始请求操作
try {
HttpGet httpGet = new HttpGet(sb.toString());
HttpResponse response = client.execute(httpGet);
int codeReturn = response.getStatusLine().getStatusCode(); // 获取返回码
if (codeReturn == HttpStatus.SC_OK) {
Log.d(TESTHTTPCLIENT, "请求成功");
HttpEntity httpEntity = response.getEntity();
return httpEntity == null ? null : EntityUtils.toString(httpEntity);
} else {
Log.d(TESTHTTPCLIENT, "请求失败");
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
二.上传下载文件
首先是上传文件的代码:
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (int index = 0; index < list.size(); index++) {
if (list.get(index).getName().equalsIgnoreCase("img") ||
list.get(index).getName().equalsIgnoreCase("headImg") ||
list.get(index).getName().equalsIgnoreCase("doc")) {
// 将NameValuePair中的地址取出,通过地址获取文件并上传
entity.addPart(list.get(index).getName(),
new FileBody(new File(list.get(index).getValue())));
Log.d("TestApp", "已经提交文件!");
} else {
// 普通文字
entity.addPart(list.get(index).getName(),
new StringBody(list.get(index).getValue()));
}
}
解释一下,首先我们需要引用两个包,我的build.gradle中是这么写的
compile files('libs/apache-mime4j-0.6.jar')
compile files('libs/httpmime-4.0.1.jar')
下载链接一会儿附上.这个代码片段,其实际意义是从传入的List<NameValuePair>中通过key筛选出文件路径的value,获取路径后直接获取文件,加入到请求头中即可!
然后说一下下载文件的问题,这里仅仅展示如何直接获取下载的文件并获取,多线程下载以及断点下载将在后边进行展示.
public static boolean doGetFileDownload(DefaultHttpClient client, String url) {
try {
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
int codeReturn = response.getStatusLine().getStatusCode(); // 获取返回码
if (codeReturn == HttpStatus.SC_OK) {
Log.d(TESTHTTPCLIENT, "请求成功");
String filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/1.doc"; // 文件路径
Log.d(TESTHTTPCLIENT, "文件保存路径:" + filePath);
File file = new File(filePath);
FileOutputStream outputStream = new FileOutputStream(file);
InputStream inputStream = response.getEntity()
.getContent();
byte b[] = new byte[1024];
int j = 0;
while ((j = inputStream.read(b)) != -1) {
outputStream.write(b, 0, j);
}
outputStream.flush();
outputStream.close();
return true;
} else {
Log.d(TESTHTTPCLIENT, "请求失败");
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
三.提交Cookie
首先需要创建CookieStore这个变量,
private static CookieStore cookieStore = null;
作为一个缓存,然后我们先获取一次缓存,存到变量中,
cookieStore = client.getCookieStore();
最后我们加到请求中并提交:
// 取出Cookie并添加到请求头
if (cookieStore != null) {
client.setCookieStore(cookieStore);
Log.d("TestApp", "提交Cookie完毕!" + cookieStore.toString());
} else {
Log.d("TestApp", "提交Cookie时,未获取到cookie");
}
到这里,这篇文章正是完成!