我在AsyncTask中有以下代码
try {
URL url = new URL(Constants.REST_URL + "signIn");
String jsonString = "{regId:" + regId + "}";
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "");
conn.setRequestProperty("Host", Constants.HOST);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Accept", "application/json, text/plain, */*");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(jsonString.length()));
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString((userName + ":" + encryptedPassword).getBytes(), Base64.DEFAULT));
conn.setDoOutput(true);
conn.setDoInput(true);
conn.getOutputStream().write(jsonString.getBytes("UTF-8"));
conn.connect();
int responseCode = conn.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder stringBuilder = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
stringBuilder.append(inputLine);
in.close();
conn.disconnect();
String responseString = stringBuilder.toString();
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
JSONObject jsonResponse = new JSONObject(responseString.toString());
user = new User();
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
user.setUserId(new BigInteger(jsonResponse.optString("userId")));
user.setUserName(jsonResponse.optString("userName"));
user.setUserEmail(jsonResponse.optString("userEmail"));
user.setUserLevel(Integer.valueOf(jsonResponse.optString("userLevel")));
return user;
} catch (MalformedURLException e) {
error = true;
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
error = true;
e.printStackTrace();
} catch (IOException e) {
error = true;
e.printStackTrace();
} catch (JSONException e) {
error = true;
e.printStackTrace();
}
return null;
和我的Nodejs服务器中的以下内容
router.post('/', function(req, res) {
console.log("body: ", req.body);
console.log("headers: ", req.headers);
console.log(req.user);
res.status(200).send(req.user).end();
});
当我通过浏览器发布http帖子时,一切都很好。但是,当我尝试从我的android应用程序发布http帖子时,我得到以下输出。
{ [SyntaxError: Unexpected token r]
body: '\r\n{regId:APA91bGRb3Ad70sqWSUlNl4Jp2_EFLv8wXKW5dwUay3rSfsLPPbqD_XQQofWtw2q27e8bjz5ZEYAC5zL-uaD3UofiplnrJBNp8IL888XveAByZdOA63A9zoktgOTurcaBkow40bnZKMN6lZZzvuVGAZ0L3UOraSVYRJ1qSb6kQhFL7BglCSmM8',
status: 400 }
我究竟做错了什么?提前致谢。
至少您的JSON字符串无效。它应该读
{"regId": "APA91bGRb3Ad70sqWSUlNl4....."}
您必须正确编码JSON字符串。
由于您已经在使用org.json
,因此可以构建输入JSON字符串,如下所示:
JSONObject json = new JSONObject();
json.putString("regId", regId);
String jsonString = json.toString();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句