我无法将带有httpUrlConnection的android应用中的json发布到NodeJs服务器

亚历山大·亚历山大(AlexandrosakisAlexandros)

我在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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将带有Curl的JSON发布到Rails服务器会给出ParseError -795

无法将带有二进制文件的POST发布到Node.js Express服务器

使用HttpUrlConnection将值发布到Android中的服务器

将带有文本的图像发布到android应用程序中的linkedIn

无法将数据从表单发布到nodeJS服务器

无法从android应用中的服务器获取json数据

在Flask中将带有Jquery和JSON的Javascript数组从客户端传递到服务器端

无法将带有 .app 扩展名的 DNS 连接到我的 apache 服务器

将带有任何Web服务器(例如nginx)的静态AngularJS网站打包到单个rpm包中

无法在Android中使用OkHttp3将JSON发布到服务器Express js

用于编码“UTF8”的无效字节序列:当我尝试将带有 FormData 对象的图像发布到服务器时,响应为 0x00

我是否应该将带有打印语句的应用发布到App Store?

无法将JSON发布到Titan Appcelerator中的服务器

带有本地 nodejs 服务器的 Android Volley 应用程序

Android Volley将json数据发布到服务器

无法在带有 Java 的 Android Studio 中使用 HTTP POST 将 JSON 发送到我的服务器

使用请求将带有json的numpy数组发布到flask应用

如何将带有Express对象的http服务器绑定到特定的IP地址?

使用HttpClient将带有post方法的utf8内容发送到android中的服务器

如何在Android中通过POST将复杂的JSON对象发布到服务器?

如何使用retrofit2将json数据发布到android中的服务器?

如何将Android中的数据以JSON格式发布到服务器?

带有Json服务器的Extjs应用程序无法正常工作

我的Android应用无法与我的服务器通信...在我的计算机中

我的应用程序如何在没有 Web 服务器的情况下发布到 WWW?

从Android发布到服务器

Django - 将带有图像的 JSON 发送到服务器

将带有服务员服务器的 Python Flask 设为 Windows 服务时无法运行

我无法从Android“ POST”到服务器PHP