zhang
9 天以前 3ae3ce1721b1a98b17c2c602c99b7226cbd32894
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.zy.acs.manager.core.third.zkd;
 
import okhttp3.*;
 
import java.io.IOException;
 
public class HttpUtils {
 
    public static String post(String url, String data) {
        OkHttpClient client = new OkHttpClient();
        // 创建RequestBody,指定媒体类型(Content-Type)为application/json; charset=utf-8
        RequestBody body = RequestBody.create(data, MediaType.get("application/json; charset=utf-8"));
 
        // 创建Request对象
        Request request = new Request.Builder()
                .url(url) // 替换为你的API URL
                .post(body) // 使用POST方法并设置请求体
                .build();
 
        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
 
            // 获取响应体并处理,例如转换为字符串或JSON对象等
            String responseData = response.body().string();
            System.out.println(responseData); // 打印响应体数据
            return responseData;
        } catch (IOException e) {
            e.printStackTrace(); // 处理异常情况,例如网络问题或服务器错误等
        }
        return null;
    }
}