如题,在实现一个软件的登录和注册功能时,通过HttpURLConnection向后端发送post,但是后端获取到的参数的值全部为null。
前端代码
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","baijing");
jsonObject.put("password","dabaijing");
jsonObject.put("sex","0");
jsonObject.put("phone","201030");
URL url = new URL("http://10.0.2.2:8080/rightway/register");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type", "application/json;charset=UTF-8");
conn.connect();
String js = jsonObject.toString();
OutputStream out = conn.getOutputStream();
out.write(js.getBytes());
out.flush();
out.close();
if (conn.getResponseCode() == 200){
//使用字符流形式进行回复
InputStream is = conn.getInputStream();
//读取信息BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder buffer = new StringBuilder();
String readLine = "";
while ((readLine = reader.readLine()) != null) {
buffer.append(readLine);
}
is.close();
reader.close();
conn.disconnect();
Looper.prepare();
Toast.makeText(getContext(),buffer,Toast.LENGTH_SHORT).show();
Looper.loop();
}else{
Looper.prepare();
Toast.makeText(getContext(),"error",Toast.LENGTH_SHORT).show();
Looper.loop();
}
后端代码没有问题,用postman测试过,而且前端发送GET就能运行正常。求解惑!
req.setCharacterEncoding("utf-8");
// 从前端的请求中获取参数
String username = req.getParameter(Constant.USER_NAME);
String password = req.getParameter(Constant.USER_PASSWORD);
// 加密密码 如果前端加密了 后端也可不加密
password = MD5Utils.stringToMD5(password);
// 对前端传进来的性别表示做处理 0表示女 其他表示男
String sex = req.getParameter(Constant.USER_GENDER);
if (sex.equals("0")){ sex = "女"; }else{ sex = "男"; }
String phone = req.getParameter(Constant.USER_PHONE);
// 创建用户对象 方便插入数据库
User user = new User(UUIDUtils.getUUID(),username,password,sex,phone);
String pwd = userService.login(username, password); //检测用户名是否存在
JSONObject json = new JSONObject();
if (pwd == null){
userService.register(user);
json.put("code",3);
json.put("description","注册成功!");
}else {
json.put("code",4);
json.put("description","用户名已经存在!");
}
// 自定义工具类 将处理完的数据返回给前端
WriteBackUtils.write(resp,json);