HTTPClient带cookie的get请求

1.需求说明
在使用jmeter时,需要使用beanshell进行响应断言,由于jmeter没有debug功能,编写是相当痛苦
于是哥们儿想着在eclipse中进行调试
2.代码执行
想想很简单啊,就是请求接口,然后拿到响应信息,然后进行json解析判断呗
好,写完后运行完美,代码如下

JSONObject json=null;
//采用rui的方式,防止使用string由于编码格式报错
URL url=new URL(strurl);//strurl就是要访问的url
URI uri=new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
HttpClient http=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(uri);
try {
  HttpResponse response=http.execute(httpGet);//发送请求获得返回值
  HttpEntity entity=response.getEntity();//获取返回的响应信息
  json=JSONObject.fromObject(EntityUtils.toString(entity));
} catch (Exception e) {
// TODO Auto-generated catch block
  e.printStackTrace();
}
return json;

上面是get请求,一般移动端接口都是get请求,原理就是把url给接口服务器,然后拿到返回的响应信息了啊,再转为jsonobject就得了呗。
嗯,不错,往下走
3.遇到问题
出现了接口带cookie的请求,我滴妈,怎么带cookie啊,百度之……
搜到了第二天……
4.完美解决
我擦,尝试了n种方式后,终于成功了,不多说,先上代码

JSONObject json=null;
//采用rui的方式,防止使用string由于编码格式报错
URL url=new URL(strurl);
URI uri=new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
CookieStore cookieStore=new BasicCookieStore();
BasicClientCookie cookie=new BasicClientCookie("你的cookie键", "你的cookie值");
cookie.setVersion(0);
cookie.setDomain("你的ip");
cookie.setPath("你的路径");
cookieStore.addCookie(cookie);
HttpGet httpGet=new HttpGet(uri);
HttpClient http=HttpClients.custom().setDefaultCookieStore(cookieStore).build();
try {
  HttpResponse response=http.execute(httpGet);//发送请求获得返回值
  HttpEntity entity=response.getEntity();//获取返回的响应信息
  json=JSONObject.fromObject(EntityUtils.toString(entity));
} catch (Exception e) {
// TODO Auto-generated catch block
  e.printStackTrace();
}
return json;

就这样,终于跑通了……
我把有关隐私的引号里的信息修改了,改成自己的就可以
5.待优化
我是要把接口请求封装起来的,可是cookie中需要些ip和path,这怎么封装啊???
我滴神啊,这实现方法真抓狂……
目前只是跑通了,我的目的是跑通来debug我的beanshell,好了,这个问题后面继续探索!!!
先调我的beanshell去了……
6.疑问点
搜索过程中,也遇到了认为很合理,认为可以跑通的方法,但不明白到自己这怎么也跑不通,可能是服务器限制吧
方式一:
httpget增加header,把cookie放在header中
httpget.addHeader(new BasicHeader("你的cookie键","你的cookie值"));
方式二:
自己百度去……
我尝试了好几种方式,不一一记录了,可以搜到的

你可能感兴趣的:(HTTPClient带cookie的get请求)