IM试图发送一个JSON对象,看起来像这样我的服务器{“名”:乔}, ,目前我的代码看起来是这样的。然而,我在我的服务器上得到的json看起来像这样{'{“name”:joe}':''}。所以我的问题是我如何发送json,所以当我在我的服务器上收到它时,它看起来像{'name':joe}?我的服务器正在使用nodejs。我想通过request.body.name来获取该名称。任何帮助,将理解从Android的发送JSON对象HttpURLConnection的POST请求
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://10.0.2.2:3000/users/user");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
String jsonString = "{\"name\":" + this.mName + "}";
OutputStream os = conn.getOutputStream();
os.write(jsonString.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder response = new StringBuilder();
while ((output = br.readLine()) != null) {
response.append(output);
response.append('\r');
}
mes = response.toString();
conn.disconnect();
if (mes!=null && !mes.isEmpty()){
return true;
}else {
return false;
}
}catch (Exception e) {
e.printStackTrace();
}
return false;
}
编辑:改变应用/后的X WWW窗体-urlencoded为application/JSON。我不断收到FileNorFoundException,和服务器返回响应代码400
字符串jsonString = “{\” 名称\ “:” + this.mName +“}”;尝试用一些字符串jsonString =改变这种“‘名\’” + this.mName“ –