我不能将带有httpUrlConnection的Android应用程序的json发布到NodeJs服务器

时间:2014-11-23 20:09:54

标签: android node.js httpurlconnection

我在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 }

我做错了什么? 提前谢谢。

2 个答案:

答案 0 :(得分:0)

至少你的JSON字符串无效。它应该读

{"regId": "APA91bGRb3Ad70sqWSUlNl4....."}

您必须正确编码JSON字符串。

由于您已经在使用org.json,因此您可以像这样构建输入JSON字符串:

JSONObject json = new JSONObject();
json.putString("regId", regId);
String jsonString = json.toString();

答案 1 :(得分:0)

我恢复代码使用JSONObject insead of string如你所说,但我遇到了同样的问题。问题出在授权标题上。我使用Base64.DEFAULT

编码它
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString((userName + ":" + encryptedPassword).getBytes(), Base64.DEFAULT));

并且新行字符位于字符串的末尾。我将其更改为

String authorization = Base64.encodeToString((userName + ":" + encryptedPassword).getBytes("UTF-8"), Base64.NO_WRAP);
conn.setRequestProperty("Authorization", "Basic " + authorization);

一切正常。非常感谢。