1

I have the following code in an 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;

and the following in my Nodejs server

 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();
 });     

When i make the http post from a browser everything is fine. But when i'm trying to make the http post from my android app i get the following output.

{ [SyntaxError: Unexpected token r]
  body:          '\r\n{regId:APA91bGRb3Ad70sqWSUlNl4Jp2_EFLv8wXKW5dwUay3rSfsLPPbqD_XQQofWtw2q27e8bjz5ZEYAC5zL-uaD3UofiplnrJBNp8IL888XveAByZdOA63A9zoktgOTurcaBkow40bnZKMN6lZZzvuVGAZ0L3UOraSVYRJ1qSb6kQhFL7BglCSmM8',
  status: 400 }

What am i doing wrong? Thanks in advance.

2 Answers2

0

At least your JSON string is invalid. It should read

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

You have to encode your JSON string correctly.

As you're already using org.json, you could build the input JSON string like this:

JSONObject json = new JSONObject();
json.putString("regId", regId);
String jsonString = json.toString();
hgoebl
  • 12,637
  • 9
  • 49
  • 72
  • It doesn't work @hgoebl. I had it like this before and i change it to try this [solution](http://stackoverflow.com/questions/21846310/sending-a-post-request-with-json-from-android-to-a-node-js-server) – Alexandrakis alexandros Nov 23 '14 at 21:10
  • @user2815062 This is definitely the answer to this specific question of the cause of `SyntaxError: Unexpected token r`. If you do this and are still having issues, please post a new question. – loganfsmyth Nov 24 '14 at 01:31
0

I revert the code to use JSONObject insead of string as you said but i had the same issue. The problem was on the authorization header. I was encoding it using Base64.DEFAULT

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

and a new line character was at the end of the string. I change it to

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

and all works fine. Thanks a lot.