OkHttp之post请求

本文详细介绍了如何使用OkHttp库在Android中发送POST请求,包括JSON、表单数据(文本、图文混传)和x-www-form-urlencoded格式的数据。通过示例代码展示了各种请求方式的实现,适用于不同的数据传输需求。
ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

post传json

String url = "";
OkHttpClient client = new OkHttpClient();
        
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("username","admin");
    jsonObject.put("password","123456");
} catch (JSONException e) {
    e.printStackTrace();
}
        
RequestBody body = RequestBody.create(jsonObject.toString(),MediaType.parse("application/json;charset=utf-8"));
Request requst = new Request.Builder()
        .url(url)
        .post(body)
        .build();
client.newCall(requst).enqueue(new Callback() {
    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        Log.e(TAG, "onFailure: " + e );
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        Log.e(TAG, "onResponse: " + response.body().string() );
    }
});

post传formdata(只传文本)

String url = "";
OkHttpClient client = new OkHttpClient();
RequestBody body = new MultipartBody.Builder()
        .addFormDataPart("username","admin")
        .addFormDataPart("password","123456")
        .build();

Request requst = new Request.Builder()
        .url(url)
        .post(formBody)
        .build();
client.newCall(requst).enqueue(new Callback() {
    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        Log.e(TAG, "onFailure: " + e );
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        Log.e(TAG, "onResponse: " + response.body().string() );
    }
});

post传formdata(图文混传)

String url = "";
OkHttpClient client = new OkHttpClient();
        
File file = new File(getFilesDir() + "/your_file_name");
RequestBody filebody = RequestBody.create(MediaType.parse("image/png"),file);
RequestBody body = new MultipartBody.Builder()
        .addFormDataPart("username","admin")
        .addFormDataPart("password","123456")
        .addFormDataPart("file","filename",filebody)
        .build();

Request requst = new Request.Builder()
        .url(url)
        .post(body)
        .build();
client.newCall(requst).enqueue(new Callback() {
    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        Log.e(TAG, "onFailure: " + e );
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        Log.e(TAG, "onResponse: " + response.body().string() );
    }
});

post传x-www-form-urlencoded

String url = "";
OkHttpClient client = new OkHttpClient();

FormBody formBody = new FormBody.Builder().build();
Request requst = new Request.Builder()
        .url(url)
        .post(formBody)
        .build();
client.newCall(requst).enqueue(new Callback() {
    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        Log.e(TAG, "onFailure: " + e );
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        Log.e(TAG, "onResponse: " + response.body().string() );
    }
});

post啥也不传,以类似get的@Query方式请求

String url = "";
OkHttpClient client = new OkHttpClient();

Request requst = new Request.Builder()
         .url(url)
         .post(RequestBody.create("",null))
         .build();
         
client.newCall(requst).enqueue(new Callback() {
     @Override
     public void onFailure(@NotNull Call call, @NotNull IOException e) {
         Log.e(TAG, "onFailure: " + e );
     }

     @Override
     public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
         Log.e(TAG, "onResponse: " + response.body().string() );
     }
 });

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

在现代 Java 开发里,使用 OkHttp 发送 POST 请求是常见的与外部服务进行数据交互的方式。结合相关参考内容,实现方法如下: ### 1. 添加依赖 在项目的 `pom.xml` 中添加 OkHttp 依赖: ```xml <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.4.1</version> </dependency> ``` 此依赖能让项目使用 OkHttp 库来处理 HTTP 请求[^3]。 ### 2. 发送 POST 请求示例 以下为一个使用 OkHttp 发送 POST 请求并携带 JSON 数据的示例代码: ```java import okhttp3.*; import java.io.IOException; public class OkHttpUtil { public static String doPostHttpRequest(String url, String json) throws IOException { OkHttpClient client = new OkHttpClient(); MediaType JSON = MediaType.get("application/json; charset=utf-8"); RequestBody body = RequestBody.create(json, JSON); Request request = new Request.Builder() .url(url) .post(body) .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } } ``` ### 3. 在 Controller 层使用示例 ```java import com.alibaba.fastjson.JSONObject; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api") public class OrderController { /** * 添加订单 */ @PostMapping("/addOrders") public Message addOrder(@RequestBody RegistrationOrder registrationOrder) { String url = "http://47.92.69.68:8888/chh/order/lockRoom"; JSONObject map = new JSONObject(); map.put("pmsTypeId", registrationOrder.getRo_type_id()); map.put("hotelCode", registrationOrder.getHi_id()); map.put("roomNo", registrationOrder.getRo_id()); map.put("orderCode", registrationOrder.getOr_id()); map.put("occupationId", registrationOrder.getRo_occupation_id()); try { String str = OkHttpUtil.doPostHttpRequest(url, map.toString()); System.out.println(JSONObject.parse(str)); // 处理业务逻辑 // registrationOrderService.addOrder(registrationOrder); } catch (IOException e) { e.printStackTrace(); } return Message.success(); } } ``` 在上述代码中,`OkHttpUtil` 类中的 `doPostHttpRequest` 方法封装了使用 OkHttp 发送 POST 请求的逻辑。在 `OrderController` 里,调用该方法发送 POST 请求并处理响应结果[^2]。
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值