一:引入依赖
com.squareup.okhttp3
okhttp
3.2.0
二:编写代码
import okhttp3.*;
import java.io.IOException;
public class HttpClient {
private static OkHttpClient client = new OkHttpClient();
public static void main(String[] args) throws IOException {
//post请求
FormBody formBody = new FormBody.Builder().add("code","1234").add("name","zp").add("age","25").build();
Request request = new Request.Builder().url("http://127.0.0.1:8082/kabaouser/es/ok").
addHeader("Access-User-Token","e5cHLWScbto3VfvYTU1llVZgl/WniA4QZZ8epmn8k/o=").post(formBody).build();
client.newCall(request).enqueue(new Callback() {
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
public void onResponse(Call call, Response response) throws IOException {
if(response.code() >= 200 && response.code() < 300) {
System.out.println(response.body().string());
}
}
});
//get请求
Request request1 = new Request.Builder().url("http://www.baidu.com").build();
client.newCall(request1).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.code() >= 200 && response.code() < 300) {
System.out.println(response.body().string());
}
}
});
}
}
三:查看返回结果