OkHttp Post提交json数据

new Thread() {
            @Override
            public void run() {
                // @Headers({"Content-Type:application/json","Accept: application/json"})//需要添加头
                MediaType JSON = MediaType.parse("application/json;charset=utf-8");
                JSONObject json = new JSONObject();
                try {
                    json.put("EngineerId", getString(ShareFile.UID, ""));
                    json.put("EngorderNumber", orderNumber);
                    json.put("PID", pid);
                    json.put("RefundType", RefundType);
                    json.put("RefundReason", reason_text.getText().toString());
                    json.put("RefundImg", str);
                    json.put("RefundVideo", "");
                    json.put("discount", discount);
                    json.put("RefundState", "0");
                    json.put("shopkeeperId", shopkeeperId);
                    json.put("payMoney", ActualPayment);//tuikuanPriceString
                    json.put("refundNum", number);
                    json.put("RefundCategory", RefundCategory);
                    json.put("sidd", oldsidd + "");
                    if (RefundCategory.equals("2")) {
                        json.put("ExchangePID", pid);
                        json.put("ExchangeSidd", sidd + "");
                    } else {
                        json.put("ExchangePID", "");
                        json.put("ExchangeSidd", "");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //申明给服务端传递一个json串
                //创建一个OkHttpClient对象
                OkHttpClient okHttpClient = new OkHttpClient();
                //创建一个RequestBody(参数1:数据类型 参数2传递的json串)
                //json为String类型的json数据
                RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
                //创建一个请求对象
//                        String format = String.format(KeyPath.Path.head + KeyPath.Path.waybillinfosensor, username, key, current_timestamp);
                Request request = new Request.Builder()
                        .url(NetUtil.saveEngRefundInfo())
                        .post(requestBody)
                        .build();

                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //DialogUtils.showPopMsgInHandleThread(Release_Fragment.this.getContext(), mHandler, "数据获取失败,请重新尝试!");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String string = response.body().string();
                        Log.i("info",string+"");
                        try {
                            JSONObject json = new JSONObject(string);
                            strddd = json.optString("msg");
                            handler.sendEmptyMessage(0x11);
                            if (json.optString("flag").equals("00")) {
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }.start();
### Android 中 OkHttp3 POST 请求提交 JSON 数据 为了实现通过 OkHttp3 库以 POST 方式向服务器发送 JSON 数据,在构建 `RequestBody` 对象时需指定媒体类型为 `"application/json; charset=utf-8"` 并传入 JSON 字符串表示形式的数据[^3]。 下面是一个完整的代码片段用于展示如何创建并执行这样的 HTTP 请求: ```java import okhttp3.*; import org.json.JSONException; import org.json.JSONObject; public class PostJsonExample { private static final String URL = "https://example.com/api/login"; public void performPostRequest() { OkHttpClient client = new OkHttpClient(); JSONObject json = new JSONObject(); try { json.put("username", "testUser"); json.put("password", "securePassword!"); } catch (JSONException e) { e.printStackTrace(); } RequestBody body = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), json.toString() ); Request request = new Request.Builder() .url(URL) .post(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // Handle failure here... } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); // Process successful responses here... } }); } } ``` 此段程序首先定义了一个目标URL地址作为 API 的端点。接着,利用 `JSONObject` 来构造要传递给服务端的信息体,并将其转换成字符串格式以便于在网络上传输。之后,这些信息被封装到 `RequestBody` 实例中并通过 `.post()` 方法附加至新的 `Request` 构建器实例上。最后一步是调用 `enqueue(Callback)` 函数来发起异步请求,这允许应用程序继续运行而不必等待网络操作的结果返回。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值