OkHttp框架是java模擬發送http協議請求的框架,下面就是使用該框架簡單編寫get請求和post請求。
1、首先是添加坐標
在項目pom.xml文件中添加坐標內容如下:
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
</dependencies>
保存后如下:
2、get請求
get請求示例如下:
package com.forest.okHttp; import java.io.IOException; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class OkHttpDemo { public static void main(String[] args) throws Exception { String url = "http://localhost/visitor/login.html"; //練習的時候換成實際存在的、不帶參數的get接口url即可 //1、創建OKhttpClient OkHttpClient client = new OkHttpClient(); //2、構建request Request request = new Request.Builder() .url(url) .get() .build(); //3、使用client發送一個請求,返回一個響應 Response response = client.newCall(request).execute(); System.out.println(response.code()); System.out.println(response.headers()); System.out.println(response.body().string()); } }
3、post請求示例如下:
package com.forest.okHttp; import java.io.IOException; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class OkHttpDemo2 { public static void main(String[] args) throws Exception { String url = "http://localhost:8999/vistor/login"; //練習的時候換成實際的post接口 //1.創建okhttpclient對象 OkHttpClient client = new OkHttpClient(); //2.創建RequestBody MediaType type = MediaType.parse("application/x-www-form-urlencoded"); //該接口表單形式提交,應根據接口實際情況做替換 RequestBody body = RequestBody.create(type, "username=test&password=test123456"); //3.構建request Request request = new Request.Builder() .url(url) .post(body) .build(); //3.使用client發送一個post請求,並返回一個響應 Response response = client.newCall(request).execute(); System.out.println(response.code()); System.out.println(response.headers()); System.out.println(response.body().string()); } }