okhttp使用
前期准备
- 引入对应的jar包
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.0.1</version>
</dependency>
post请求
@Test
public void test3() {
MediaType JSON
= MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
json.put("ledger", "22");
RequestBody body = RequestBody.create(JSON, json.toJSONString());
Request request = new Request.Builder()
.url("http://localhost/cost-test-service/testGet")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println("##result##" + response.body().string());
} catch (Exception e) {
}
}
登录后发送post请求
@Test
public void test5() throws Exception {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.cookieJar(new CookieJar() {
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
Map<String, Object> map = new HashMap<>();
int i = 0;
for (Cookie cookie : cookies) {
System.out.println("name:" + cookie.name() + " value:" + cookie.value());
map.put(cookie.name(), cookie.value());
}
try {
saveToFile(map);
} catch (Exception e) {
System.out.println("序列化出现异常");
}
System.out.println("cookies#" + JSONObject.toJSONString(cookies.size()));
cookieStore.put(url.host(), cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
System.out.println("cookies1#" + JSONObject.toJSONString(cookies));
return cookies != null ? cookies : new ArrayList<Cookie>();
}
});
OkHttpClient client = builder.build();
final MediaType JSON
= MediaType.get("application/json; charset=utf-8");
String url = "http://localhost/login";
Map<String, String> map = new HashMap<>();
map.put("key", "10");
map.put("authType", "pwd");
map.put("userName", "test");
map.put("userPwd",
"AE005C33C768E5A07C0B309FAC82438F3BF85339C50B6694C64EF72B1A2FDF60FC9088FDB0BEC4095E8785DF06D4D89D93EF4FA7F1CCC0347F9CB0EE1A7FC700C344F887D6BB52FDFE9F2B4673A57CEB73A8CDC0AC6A01EE0227BB0DF74AE2654A4F62B234E389F2E8C746");
RequestBody body = RequestBody.create(JSON, JSONObject.toJSONString(map));
Request request = new Request.Builder()
.url(url)
.addHeader("Referer", "http://localhost/?v=" + new Date().getTime())
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(JSONObject.toJSONString(response.body().string()));
}
}
public void saveToFile(Map<String, Object> cookies) throws Exception {
File f = new File("a.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(f));
out.write(JSONObject.toJSONString(cookies));
out.close();
}
//从文件中读取存储的cookie信息
public JSONObject readFromFile() throws Exception {
File f = new File("a.txt")
BufferedReader br = new BufferedReader(new FileReader(f))
String lineTxt = ""
String readLine
while ((readLine = br.readLine()) != null) {
lineTxt += readLine
}
System.out.println(lineTxt)
JSONObject jsonObject
if (StringUtils.isEmpty(lineTxt)) {
jsonObject = new JSONObject()
} else {
jsonObject = JSONObject.parseObject(lineTxt)
}
br.close()
return jsonObject
}
//使用刚才存储的文件进行请求验证
@Test
public void test6() throws Exception {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
builder.cookieJar(new CookieJar() {
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>()
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
Map<String, Object> map = new HashMap<>()
int i = 0
for (Cookie cookie : cookies) {
System.out.println("name:" + cookie.name() + " value:" + cookie.value())
map.put(cookie.name(), cookie.value())
}
System.out.println("cookies
cookieStore.put(url.host(), cookies)
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host())
cookies = cookies != null ? cookies : new ArrayList<Cookie>()
try {
JSONObject json = readFromFile()
if (!json.isEmpty()) {
Set keys = json.keySet()
for (Object key : keys) {
Cookie cookie = new Cookie.Builder().name((String) key).value(json.getString((String) key)).domain(url.host()).build()
// Cookie cookie = new Cookie(key,json.getString((String)key),new Date().getTime()+1000000L,"","/")
cookies.add(cookie)
// Cookie cookie=CookieJar.
}
}
} catch (Exception e) {
e.printStackTrace()
}
System.out.println("cookies1
return cookies != null ? cookies : new ArrayList<Cookie>()
}
})
OkHttpClient client = builder.build()
final MediaType JSON
= MediaType.get("application/json
// OkHttpClient client = new OkHttpClient()
String url = "http://localhost/cost-test-service/queryList"
Map<String, String> map = new HashMap<>()
map.put("key", "10")
String param = "{\"currentPage\":1,\"pageSize\":6}"
RequestBody body = RequestBody.create(JSON, param)
Request request = new Request.Builder()
.url(url)
.addHeader("Referer", "http://localhost")
.post(body)
.build()
try (Response response = client.newCall(request).execute()) {
System.out.println(JSONObject.toJSONString(response.body().string()))
}
}
get请求
@Test
public void testtms() throws Exception{
OkHttpClient client = new OkHttpClient();
File f = new File("b.txt");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String readLine;
int i=0;;
while ((readLine = br.readLine()) != null) {
System.out.print(++i+"deptId#"+readLine+"#");
if(i%50==0){
Thread.sleep(1000);
}
Request request = new Request.Builder()
.url("http://localhost/cost-test-service/dept?orgId="+readLine)
.build();
try (Response response = client.newCall(request).execute()) {
String string = response.body().string();
System.out.println(string);
} catch (Exception e) {
}
}
}
参考: