首先,你需要在项目的`build.gradle`文件中添加OkHttp的依赖:
```groovy
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
}
```
然后,你可以使用以下代码发送一个GET请求:
```java
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpGetExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.example.com/data")
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String responseBody = response.body().string();
System.out.println("响应内容: " + responseBody);
} else {
System.out.println("请求失败,错误码: " + response.code());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请将`https://api.example.com/data`替换为你想要请求的URL。
以下是重构后的内容:
1. 创建一个名为`testOkHttpClient`的方法,用于测试OkHttpClient的功能。
```java
public void testOkHttpClient() {
// ...
}
```
2. 在方法内部,定义所需的变量。
```java
String url = "http://127.0.0.1:80";
Request request = new Request.Builder().url(url).header("func", "test").build();
OkHttpClient okHttpClient = new OkHttpClient();
Call call = okHttpClient.newCall(request);
Response response;
ResponseBody responseBody;
```
3. 使用try-catch语句执行请求。
```java
try {
response = call.execute();
} catch (IOException e) {
e.printStackTrace();
return; // 如果发生异常,直接返回,不进行后续的断言验证
}
```
4. 使用断言验证请求是否成功、响应头和响应体的内容等信息。
```java
// ...(省略了之前的断言代码)
// 获取响应体内容
responseBody = response.body();
if (responseBody != null) {
assertTrue(responseBody.string().length() > 0);
}
```
5. 将以上代码组合在一起,得到完整的`testOkHttpClient`方法。
```java
public void testOkHttpClient() {
String url = "http://127.0.0.1:80";
Request request = new Request.Builder().url(url).header("func", "test").build();
OkHttpClient okHttpClient = new OkHttpClient();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
// ...(省略了之前的断言代码)
// 获取响应体内容
responseBody = response.body();
if (responseBody != null) {
assertTrue(responseBody.string().length() > 0);
}
} catch (IOException e) {
e.printStackTrace();
return; // 如果发生异常,直接返回,不进行后续的断言验证
}
}
```
发起 POST JSON 请求
要发起一个 POST JSON 请求,我们通常使用 HTTP 库(如 Python 的 requests 库)来实现。以下是一个简单的示例,展示了如何使用 Python 的 requests 库发起一个 POST
JSON 请求:
```python
import requests
import json
url = 'https://your-api-endpoint.com/api' # 请替换为实际的 API 端点 URL
data = {
'key1': 'value1',
'key2': 'value2',
} # 请根据实际需求添加或修改数据
headers = {'Content-Type': 'application/json'} # 设置请求头为 JSON 格式
response = requests.post(url, data=json.dumps(data), headers=headers)
# 如果需要检查响应状态码和内容,请取消注释以下两行
# print('Status Code:', response.status_code)
# print('Response Content:', response.json())
```
在上述示例中,首先导入了 `requests` 和 `json` 库。然后定义了 API 端点的 URL、要发送的数据以及请求头。接着使用 `requests.post()` 函数发起 POST 请求,将数据转换为 JSON 格式并作为参数传递给该函数。最后,可以查看响应的状态码和内容(如果需要)。
以下是重构后的代码,我将每个部分单独提取出来以提高可读性:
```java
import okhttp3.*;
import org.junit.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
public class PostJsonTest {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
@Test
void postJson() throws IOException {
// 创建请求
String url = "http://127.0.0.1:80";
String postBodyJson = "{\"name\":\"tony\",\"age\":18}";
RequestBody requestBody = createRequestBody(postBodyJson, JSON);
Request request = createOkHttpClient().newBuilder()
.url(url)
.header("token", "123abc")
.post(requestBody)
.build();
// 将请求体内容写入 buffer
Buffer buffer = new Buffer();
Objects.requireNonNull(request.body()).writeTo(buffer);
// 获取请求体内容格式,然后从 buffer 中读出
MediaType contentType = requestBody.contentType();
Charset charset = Objects.requireNonNull(contentType).charset();
assertEquals(postBodyJson, buffer.readString(charset), "请求体写入跟读出不一致");
}
private static RequestBody createRequestBody(String json, MediaType jsonMediaType) throws UnsupportedEncodingException {
return RequestBody.create(jsonMediaType, json);
}
private static OkHttpClient createOkHttpClient() {
return new OkHttpClient();
}
}
```
要发送一个使用 application/x-www-form-urlencoded 编码类型的 POST 请求,可以使用 Java 的 HttpURLConnection 类来实现。以下是一个简单的示例:
1. 首先,创建一个 URL 对象,传入目标服务器的地址;
2. 然后,通过该 URL 对象的 openConnection() 方法创建一个 HttpURLConnection 对象;
3. 接着,设置 HttpURLConnection 对象的请求方法为 POST;
4. 设置 Content-Type 为 application/x-www-form-urlencoded;
5. 设置字符编码为指定的编码类型,例如 "UTF-8";
6. 最后,通过 HttpURLConnection 对象的 getOutputStream() 方法获取输出流,并将请求参数写入输出流;
7. 通过 HttpURLConnection 对象的 getInputStream() 方法获取输入流,读取服务器返回的数据。
以下是具体的代码实现:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// 创建 URL 对象
URL url = new URL("http://example.com/post");
// 创建 HttpURLConnection 对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 POST
connection.setRequestMethod("POST");
// 设置 Content-Type 为 application/x-www-form-urlencoded
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置字符编码为指定的编码类型,例如 "UTF-8"
connection.setRequestProperty("charset", "UTF-8");
// 设置允许输出
connection.setDoOutput(true);
// 将请求参数写入输出流
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
String postParameters = "param1=value1¶m2=value2";
outputStream.writeBytes(postParameters);
outputStream.flush();
outputStream.close();
// 获取服务器返回的数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出服务器返回的数据
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
```java
public static final MediaType FORM = MediaType.get("application/x-www-form-urlencoded; charset=utf-8");
@Test
void postJson() {
// 创建请求
String url = "http://127.0.0.1:80";
// 构造参数
Map
stringObjectMap.put("name", "tony");
stringObjectMap.put("age", 18);
// 塞入参数
StringBuilder stringBuilder = new StringBuilder();
stringObjectMap.forEach((key, val) -> {
if (0 != stringBuilder.length()) {
stringBuilder.append("&");
}
stringBuilder.append(String.format("%s=%s", key, val));
});
// 请求参数构造请求体
RequestBody requestBody = RequestBody.create(stringBuilder.toString(), FORM);
Request request = new Request.Builder().url(url).header("token", "123abc").post(requestBody).build();
OkHttpClient okHttpClient = new OkHttpClient();
Call call = okHttpClient.newCall(request);
try {
// 执行请求
Response response = call.execute();
assertTrue(response.isSuccessful(), "请求失败");
// 将请求体内容写入 buffer
Buffer buffer = new Buffer();
Objects.requireNonNull(request.body()).writeTo(buffer);
// 获取请求体内容格式,然后从 buffer 中读出
MediaType contentType = requestBody.contentType();
Charset charset = Objects.requireNonNull(contentType).charset();
assert charset != null;
assertEquals("name=tony&age=18", buffer.readString(charset), "请求体写入跟读出不一致");
} catch (IOException e) {
e.printStackTrace();
}
}
```
要发送一个 `POST` 请求,使用 `application/x-www-form-urlencoded` 编码类型,可以使用 Java 编程语言中的
`HttpURLConnection` 类来实现。以下是示例代码:
```java
import java.io.*;
import java.net.*;
public class PostRequestExample {
public static void main(String[] args) throws IOException {
String url = "https://example.com/api"; // 替换为实际的 API URL
String postData = "param1=value1¶m2=value2"; // 替换为实际的 POST 数据
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为 POST
con.setRequestMethod("POST");
// 设置请求头信息
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(postData.getBytes().length));
// 启用输出流以便写入请求数据
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
// 写入请求数据
writer.write(postData);
writer.flush();
writer.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader reader = null;
InputStream inputStream = null;
try {
// 从服务器读取响应数据
inputStream = con.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
reader = new BufferedReader(inputStreamReader);
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
// 输出响应内容
System.out.println("Response Content: " + content.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭输入输出流和连接对象
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (con != null) {
con.disconnect();
}
}
}
}
```
```java
@Testvoid postJson() {
// 创建请求
String url = "http://127.0.0.1:80";
// 构造参数
Map
stringObjectMap.put("name", "tony");
stringObjectMap.put("age", 18);
// 塞入参数
FormBody.Builder builder = new FormBody.Builder();
stringObjectMap.forEach((key, val) -> builder.add(key, String.valueOf(val)));
// 请求参数构造请求体
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.url(url)
.header("token", "123abc")
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
Call call = okHttpClient.newCall(request);
try {
// 执行请求
Response response = call.execute();
assertTrue(response.isSuccessful(), "请求失败");
// 将请求体内容写入 buffer
Buffer buffer = new Buffer();
Objects.requireNonNull(request.body()).writeTo(buffer);
// 获取请求体内容格式,然后从 buffer 中读出
MediaType contentType = requestBody.contentType();
Charset charset = Objects.requireNonNull(contentType).charset();
assertNull(charset);
assertEquals("name=tony&age=18", buffer.readString(StandardCharsets.UTF_8), "请求体写入跟读出不一致");
assertNotEquals("name=tony&age=18", buffer.readString(Charset.forName("UTF-8")), "请求体写入跟读出不一致");
} catch (IOException e) {
e.printStackTrace();
}
}
```