用okhttp提交post数据(json,java,后端netcore(frombody))

发布时间 2023-09-23 23:34:46作者: 牛腩
用okhttp提交post数据(json,java,后端netcore(frombody))
2023年09月23日
点提交按钮,把拼接好的JSON字符串提交到后端接口,okhttp的github上列出来的示例就是提交POST JSON字符串的,照抄就是了,这里只是把自己写的代码列出来
https://github.com/square/okhttp
环境:
Android Studio Giraffe 2022.3.1 Patch 1,JAVA,API33,模板用那个右下角有个小图标的,后端net7
 
先贴后端代码:
        [HttpPost]
        public ApiResult Post([FromBody] Model.TiZhong model)
        {
            try
            {
                Model.TiZhong src = _tzRepository.FirstOrDefault(a => a.CreateTime.ToString("yyyy-MM-dd") == model.CreateTime.ToString("yyyy-MM-dd"));
                if (src != null) {
                    throw new System.Exception("当天已经录入有体重了!!!");
                }
                _tzRepository.Insert(model);
                return new ApiResult() { code=0,msg="新增体重记录成功。" };
            }
            catch (System.Exception ex)
            {
                return new ApiResult() { code = 1, msg = ex.Message };
            }
        }

 

android studio里提交按钮的代码:
public static final MediaType JSON = MediaType.get("application/json");

  //新增
        binding.btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String time = binding.txtTime.getText().toString();
                String zl = binding.txtZL.getText().toString();
                String img = binding.tvres.getText().toString();

                AlertDialog.Builder dialog = new AlertDialog.Builder(SecondFragment.this.getContext());
                dialog.setTitle("是否确认提交?");
                dialog.setMessage("时间:" + time + "\n重量(公斤):" + zl + "\n图片:" + img);
                dialog.setCancelable(false);
                dialog.setPositiveButton("提交", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // Android 4.0 之后不能在主线程中请求HTTP请求
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                OkHttpClient client = new OkHttpClient();
                                //POST
                                String jsonstr = "{\n" +
                                        "    \"Id\":0,\n" +
                                        "    \"CreateTime\":\"" + time + "\",\n" +
                                        "    \"ZhongLiang\":" + zl + ",\n" +
                                        "    \"Img\":\"" + img + "\"\n" +
                                        "}";

                                RequestBody requestBody = RequestBody.create(jsonstr, JSON);
                                Request request = new Request.Builder().url("http://www.badk.net/appapi/tizhong").post(requestBody).build();
                                //GET
//                Request request = new Request.Builder()
//                        .url("http://www.baidu.com")
//                        .build();
//
                                try {
                                    Response response = client.newCall(request).execute();
                                    String responseData = response.body().string();
                                    Log.i(TAG, "调用远程接口返回: " + responseData);
                                    SecondFragment.this.getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            AlertDialog.Builder dialog = new AlertDialog.Builder(SecondFragment.this.getContext());
                                            dialog.setTitle("提交结果:");
                                            dialog.setMessage(responseData);
                                            dialog.show();
                                            binding.txtTime.setText("");
                                            binding.txtZL.setText("");
                                        }
                                    });
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }).start();
                        //多线程提交数据 结束
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                dialog.show();


            }
        });