<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.7.2</version>
</dependency>
@Component
@Slf4j
public class OkHttpUtil {
public String appJsonSync(String url, String param) {
try {
log.warn("appJsonSync <-- url: {},param: {}", url, param);
OkHttpClient okHttpClient = new OkHttpClient();
okhttp3.RequestBody requestBody = okhttp3.RequestBody
.create(param, MediaType.parse("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response execute = okHttpClient.newCall(request).execute();
ResponseBody body = execute.body();
return body != null ? body.string() : null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void appJsonAsync(String url, String param) {
try {
log.warn("appJsonAsync <-- url: {}, param: {}", url, param);
OkHttpClient okHttpClient = new OkHttpClient();
okhttp3.RequestBody requestBody = okhttp3.RequestBody
.create(param, MediaType.parse("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
log.warn("call: {}, response: {}", call, Objects.requireNonNull(response.body()).string());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
String url = "http://127.0.0.1:port/ooxx/userLoginAuth";
HashMap<String, Object> map = new HashMap<>();
map.put("loginName", "user1");
map.put("authKey", "123");
String result = HttpUtil.post(url, map);
String url = "http://127.0.0.1:port/ooxx/sync";
HashMap<String, Object> map = new HashMap<>();
map.put("appId", "131409040112");
map.put("deptI1d", "19910769053");
String result = HttpUtil.post(url, gson.toJson(map));
String url = "http://127.0.0.1:port/ooxx/userLoginAuth";
HashMap<String, Object> map = new HashMap<>();
map.put("loginName", "user1");
map.put("authKey", "123");
String result = HttpRequest.post(url)
.header("X-Ticket", "7e35e53fa44f987f9297ff6b3a8fd568f1")
.header("ClientTag", "OUTNET_BROWSE")
.form(map)
.timeout(20000)
.execute().body();
String url = "http://127.0.0.1:port/ooxx/sync";
HashMap<String, Object> map = new HashMap<>();
map.put("appId", "user1");
map.put("deptId", "123");
String result = HttpRequest.post(url)
.header("X-Ticket", "7e35e53fa443184c71047204d1330a8f1d")
.header("ClientTag", "OUTNET_BROWSE")
.body(gson.toJson(map))
.timeout(20000)
.execute().body();