构成JSON对象并调用Async
方法的代码:
final String OWNER_PASSWORD="ownerPassword";
final String OWNER_EMAIL="ownerEmailId";
private void CheckPassword() {
shopkeeperJSON = new JSONObject();
try{
shopkeeperJSON.put(OWNER_EMAIL,"varuncr7raj@gmail.com");
shopkeeperJSON.put(OWNER_PASSWORD,"1");
} catch (JSONException e) {
e.printStackTrace();
}
new POST_Request(this).execute("http://192.168.1.5:3000/api/CheckPassword", shopkeeperJSON.toString());
}
这是post方法的Android代码,它向我的本地服务器发送JSON对象:
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod(REQUEST_METHOD);
httpCon.setRequestProperty("Accept","application/json");
//httpCon.setRequestProperty("Content-Type", "application/json");
httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//Input
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(params[1]);
//osw.write("{ ownerEmailId : varuncr7raj@gmail.com, ownerPassword: 1 }");
osw.flush();
osw.close();
os.close(); //don't forget to close the OutputStream
httpCon.connect();
//read the inputstream and print it
String result;
BufferedInputStream bis = new BufferedInputStream(httpCon.getInputStream());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result2 = bis.read();
while(result2 != -1) {
buf.write((byte) result2);
result2 = bis.read();
}
result = buf.toString();
//System.out.println(result);
Log.e("result", result);
httpCon.disconnect();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
这是我的节点js服务器的代码。这只是记录请求的res.body。
exports.checkPassword = function(req,res){
var data = JSON.stringify(req.body);
//console.log(JSON.stringify(req.body));
var obj = JSON.parse(data);
console.log(obj);
res.send(req.body);
};
代码的输出:-
{ '{"ownerEmailId":"varuncr7raj@gmail.com","ownerPassword":"1"}': '' }
您可以看到输出,JSON对象正成为JSON对象的JSON密钥。谢谢!任何帮助将不胜感激!
所需的输出:
{"ownerEmailId":"varuncr7raj@gmail.com","ownerPassword":"1"}
答案 0 :(得分:0)
您告诉您将以x-www-form-urlencoded
的形式发送参数,但是您发送的是JSON。
更改为httpCon.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
在服务器端,尝试仅使用所需的req.body属性:
exports.checkPassword = function(req, res) {
const { ownerEmailId, ownerPassword } = req.body;
console.log(ownerEmailId, ownerPassword);
res.send(req.body);
};