我想将发帖请求从我的Android应用发送到Spring Boot。我使用okhttp以JSON发送HTTP发布请求。代码是这样的:
每次我使用Android请求发送发帖请求时,都会收到400个错误的请求参数'name'不存在“,” path“:” / newcustomer“。但是当我使用邮递员时,它会起作用。
Java
----------------------------------------------------------------
Log.d("okhttphandleruserreg", "called");
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put("name", name);
jsonObject.put("email", email);
jsonObject.put("username", username);
jsonObject.put("password", password);
jsonObject.put("month", month);
jsonObject.put("dayOfMonth", dayOfMonth);
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request.Builder builder = new Request.Builder();
builder.url(params[0]);
builder.post(body);
Request request = builder.build();
Spring Boot
-----------------------------------------------------------------
@RequestMapping(value = "/newcustomer", method= RequestMethod.POST)
public Customer newCust(@RequestParam(value="name") String name,
@RequestParam(value="email") String email,
@RequestParam(value="username") String username,
@RequestParam(value="password") String password,
@RequestParam(value="month") int month,
@RequestParam(value="dayOfMonth") int dayOfMonth
)
答案 0 :(得分:0)
您在Spring Boot中使用请求参数,但是在Android代码中,您将其作为请求正文发送。
请更改以上任意一项。最好在两个地方都使用RequestBody。
class Customer
{
String name:
String email:
String username;
String password;
int month;
int dayofthemonth;
//getter and setters
}
public Customer newCust(@RequestBody Customer newcustomer)
{
}
答案 1 :(得分:0)
实现后端 / newcustomer API的方式表明,您期望请求有效负载是请求表单数据中的原始请求参数。
假设服务器端API是您的合同,因此应保持原样,客户端代码应按以下方式更新:
Log.d("okhttphandleruserreg", "called");
// here you create your request body as as a Form one
RequestBody formBody = new FormBody.Builder()
.add("name", "test")
.add("email", "test@domain.com")
.add("username", "test")
.add("username", "test")
.add("month", "january")
.add("dayOfMonth", "1")
.build();
Request request = new Request.Builder()
.url(params[0])
.post(formBody)
.build();
// call your request