GET請求方式(默認)
package com.qf.demo7;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Test {
public static void main(String[] args) {
String path="http://localhost:8080/Day28_03/LoginServlet?useName=zhangsan&pwd=123";
// 1 創(chuàng)建okhttp客戶端對象
OkHttpClient client = new OkHttpClient();
// 2 request 默認是get請求
Request request = new Request.Builder().url(path).build();
// 3 進行請求操作
try {
Response response = client.newCall(request).execute();
// 4 判斷是否請求成功
if(response.isSuccessful()){
// 得到響應體中的身體,將其轉(zhuǎn)成 string
String string = response.body().string();
System.out.println(string);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
POST請求方式
package com.qf.demo7;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class Test3 {
public static void main(String[] args) {
String path = "http://localhost:8080/Day28_03/LoginServlet";
// 2 創(chuàng)建okhttpclient對象
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder().add("useName", "addd").add("pwd", "123").build();
// 3 創(chuàng)建請求方式
Request request = new Request.Builder().url(path).post(body).build();
// 4 執(zhí)行請求操作
try {
Response response = client.newCall(request).execute();
if(response.isSuccessful()){
String string = response.body().string();
System.out.println(string);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}