OkHttpClient

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();
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容