1 Form表单数据的传递
例如OkHttp
FormBody.Builder builder = new FormBody.Builder(); for (String s : params.keySet()) { Object v = params.get(s); builder.add(s, v != null ? v.toString() : ""); } Request request = new Request.Builder().url(url) .addHeader("content-type", "application/json;charset:utf-8") .post(builder.build()).build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { return response.message(); }
2 Json格式数据的传递
MediaType mediaType = MediaType.parse("application/json"); //使用JSONObject封装参数 JSONObject jsonObject = new JSONObject(); try { for (String s : params.keySet()) { Object v = params.get(s); jsonObject.put(s, v != null ? v.toString() : ""); } } catch (Exception e) { } //创建RequestBody对象,将参数按照指定的MediaType封装 RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString()) Request request = new Request.Builder() .url(url) .post(requestBody) .addHeader("sign", sign) .addHeader("signType", signType) .build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { return response.message(); }
如果将Form表单参数改成Json参数传递,因后台接收的方式会有所不同,接受不到前端传递的参数,因为其媒体类型(MediaType)不一样
springmvc 中requestbody 接收http请求的json数据,将json数据转换为java对象
@RequestMapping("/addOrUpdateRole") public ApiResult changeAgent(@RequestBody @Valid StaffRoleParam param, BindingResult result) throws RpcInvokingException { log.info("staff ---- >> addOrUpdateRole execute, 参数: param = {}", JSON.toJSONString(param)); }
如果没有requestbody 默认就是form表单格式的请求