小白的笔记
昨天接触cookie,做一下记录
1. 准备:
(软件部分)
PostMan:一款非常好用的网络测试软件,可以模拟连接请求,甚至可以将网络请求生成各种代码如java。搬来的使用教程:
https://blog.csdn.net/fxbin123/article/details/80428216
Fiddler : 抓包工具,搬砖来的教程:https://www.cnblogs.com/conquerorren/p/8472285.html
(理论部分-我的理解)
cookie是一种有一定格式的数据包,一般作为网络的身份标记。比如登录小米社区后,服务器会返回一个cookie,其中就包含了你的登录标识,
如:浏览器按F12,打开开发者模式。cookie在头里,一个Cookie包含很多数据,有多数是不需要的,需要你用PostMan去尝试,去掉不需要的键值对key=value。
测试小米社区关键cookie的简单办法:
按send发送。
找对cookie后,在按钮send下方有何橙色code字段,点击他,就可以选择生成的代码类型
复制后粘贴到你的项目中就可以实现啦。
如果想要实现自动评论,就需要发送带from-data的post请求,from-data也是一种键值对数据
2 部分代码
// 简单登录
static String getUrlByCookie(String urlbuf,String cookieVal) throws IOException
{
//打开一个连接
URL url = new URL(urlbuf);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (cookieVal != null) {
//发送cookie信息上去,以表明自己的身份,否则会被认为没有权限
connection.setRequestProperty("Cookie", cookieVal);
}
//connection.connect();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type","multipart/form-data;");
InputStream urlStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(urlStream));
String ss=null;
// 服务器返回结果
String total="";
while ((ss = bufferedReader.readLine())!=null){
total+=ss;
}
bufferedReader.close();
return total;
}
// 社区发送评论
static Response sendUrlWithFromData(String sUrl, String cookie, String miuiBbsMsg) throws Exception {
OkHttpClient client = new OkHttpClient();
//生成Post : from-data
MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
RequestBody body = RequestBody.create(mediaType,
"------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n"
+ "Content-Disposition: form-data; name=\"tid\"\r\n\r\n34464683\r\n"
+ "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n"
+ "Content-Disposition: form-data; name=\"fid\"\r\n\r\n389\r\n"
+ "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n"
+ "Content-Disposition: form-data; name=\"message\"\r\n\r\n" + miuiBbsMsg +"\r\n"
+ "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n"
+ "Content-Disposition: form-data; name=\"token\"\r\n\r\n\r\n"
+ "------WebKitFormBoundary7MA4YWxkTrZu0gW--");
// 生成连接
Request request = new Request.Builder()
.url(sUrl)
.post(body)
.addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
.addHeader("Cookie", cookie)
.addHeader("Host", "bbs.xiaomi.cn")
.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36")
.addHeader("X-Requested-With", "XMLHttpRequest")
.addHeader("cache-control", "no-cache")
.build();
// 返回结果
return client.newCall(request).execute();
}