我用的是httpclient-4.5.1.jar,如果httpclient版本太低的话,此方法可能用不了,需要用手工设置cookie.那种方法,暂不讨论,主要思路就是通过登陆时获取返回的cookie,再讲coolie的值填到新的请求头中,不过这种方法一般不怎么遇到,基本上对面接口都会直接返回给你一个token,你下次访问直接将这个token作为参数传过去就能获取自己想要的数据.
package test;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONArray;
public class JKTest03 {
public static void main(String[] args) throws Exception {
long st=new Date().getTime();
CloseableHttpClient http = HttpClients.createDefault();
try {
String url = "post";
HashMap<String, String> map = new HashMap<String, String>();
map.put("username", "admin");
map.put("password", "pass");
getlogin(http, map, url);//登陆验证
String url2 = "get";
String list = Get(http, url2);//获取数据
System.out.println(list);
} finally {
http.close();
}
long et=new Date().getTime();
System.out.println("共费时:"+(et-st));
// System.out.println("结束");
}
public static String getlogin(CloseableHttpClient client, Map<String, String> map, String url) throws Exception {
String body = "";
String encoding = "utf-8";
// 创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
// 装填参数,常规格式
/*
* List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (map != null) {
* for (Entry<String, String> entry : map.entrySet()) {
* //System.out.println(entry.getKey()+"=="+ entry.getValue()); nvps.add(new
* BasicNameValuePair(entry.getKey(), entry.getValue())); } } // 设置参数到请求对象中
* httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
* // 设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
*/
//参数是json格式
httpPost.setEntity(new StringEntity(JSONArray.toJSONString(map)));
// 设置header信息
// 指定报文头【Content-type】、【User-Agent】
//参数是json的需要将Content-type设为application/json
httpPost.setHeader("Content-type", "application/json");//默认是:application/x-www-form-urlencoded
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// 执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
// response.
// 获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
// 按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
// 释放链接
response.close();
return body;
}
public static String Get(CloseableHttpClient http, String url) throws Exception {
HttpGet httpget = new HttpGet(url);
String body = "";
CloseableHttpResponse response = http.execute(httpget);
// response.
// 获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
// 按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "utf-8");
}
// 释放链接
response.close();
return body;
}
}