android 中设置http请求头headers的Cookie
Posted IyangcLove
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android 中设置http请求头headers的Cookie相关的知识,希望对你有一定的参考价值。
为了验证的安全, 有些应用 会对headers设置cookie 才能进行以后的操作。网上查阅了很多资料,自己也走了些弯路 总算搞出来了 。直接上代码
class NetThr
public static String sessionid=null;
//请求的url ,json数据, 服务的类型(获取cookie)
public void netThr(String svrurl, String message,int svrType)
String svraddr = "";
svraddr = svrurl.replace(" ", "%20");
URL svr = new URL(svraddr);
if (message == null)
message = "";
try
HttpURLConnection httpreq = (HttpURLConnection) svr.openConnection();
httpreq.setConnectTimeout(60000);
httpreq.setReadTimeout(60000);
if (message.length() > 0)
httpreq.setRequestMethod("POST");
else
httpreq.setRequestMethod("GET");
httpreq.setDoInput(true);
if (message.length() > 0)
httpreq.setDoOutput(true);
httpreq.setRequestProperty("Charset", "UTF-8");
httpreq.setRequestProperty("Content-length", "" + message.getBytes("UTF-8").length);
httpreq.setRequestProperty("Content-Type", "application/json");
if (sessionid!=null&&svrType!=HandleRespFun.API_TYPE_GETCOOKIE)
//设置Cookie 到 Headers
httpreq.setRequestProperty("Cookie",sessionid);
httpreq.connect();
if (message.length() > 0)
OutputStream os = httpreq.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.write(message.getBytes("UTF-8"));
dos.close();
//返回的headers 例子
// Content-Type application/json
// Set-Cookie api_authenticated=1
// Set-Cookie user_authenticated=1
// Set-Cookie JSESSIONID=16i51l7jwmodpb1u1jfpdk0pg;Path=/laundry
// Expires Thu, 01 Jan 1970 00:00:00 GMT
// Content-Length 175
// Server Jetty(9.2.3.v20140905)
// Date Tue, 27 Jan 2015 02:32:09 GMT
//获取Cookie
if(svrType==HandleRespFun.API_TYPE_GETCOOKIE)
Map<String, List<String>> kk = httpreq.getHeaderFields();
List<String> cook = kk.get("Set-Cookie");
if(cook!=null)
for (String onecook : cook)
Log.v("Jashon", "Cookie is:" + onecook);
if (onecook.contains("JSESSIONID"))
//sessionid=JSESSIONID=16i51l7jwmodpb1u1jfpdk0pg
sessionid=onecook.split(";")[0];
之前的时候 截取 sessionid部分截取错了 这里要注意一下哦。代码有点乱,不过主要方法逻辑 还是清晰的 希望能帮到一些盆友 自己以后也会用得着
以上是关于android 中设置http请求头headers的Cookie的主要内容,如果未能解决你的问题,请参考以下文章