针对从Android应用程序到NodeJS服务器

时间:2016-11-04 12:30:45

标签: android node.js http-post session-cookies

我正在开发一个带有NodeJS后端服务器的Android应用程序。在用户登录后向不同页面发出请求时,我在验证用户时遇到问题。

登录后,我将set-cookie值存储在SharedPrefs中。现在,当我发出POST请求时,我会在标头中发送set-cookie值,即con.setRequestProperty("set-cookie", cookie);,以便使用req.user.authenticate在后​​端对用户进行身份验证。

但是,req.user未定义,因此请求失败。这可能有什么问题?感谢。

以下是我的POST请求代码。

    con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "\"Mozilla/5.0\"");

    con.setDoOutput(true);

    JSONObject jsonParam = new JSONObject();
    try {
        jsonObject.accumulate("set-cookie", cookie);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    OutputStreamWriter out = new   OutputStreamWriter(con.getOutputStream());
    out.write(jsonParam.toString());
    out.close();

    int responseCode = con.getResponseCode();
    System.out.println("Response Code:"+responseCode);

1 个答案:

答案 0 :(得分:0)

以这种格式发送数据

 String data = "";

InputStream inputStream = null;


try{

    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("set-cookie", cookie);


    data = jsonObject.toString();
    Log.d("json data",data);
    // 1. create HttpClient
    HttpClient httpclient = new DefaultHttpClient();

    // 2. make POST request to the given URL
    HttpPost httpPost = new HttpPost(CHECK_WEBSERVICE_URL);
    StringEntity se = new StringEntity(data);

    // 6. set httpPost Entity
    httpPost.setEntity(se);

    // 7. Set some headers to inform server about the type of the content
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");

    // 8. Execute POST request to the given URL
    HttpResponse httpResponse = httpclient.execute(httpPost);

    // 9. receive response as inputStream
    inputStream = httpResponse.getEntity().getContent();

    // 10. convert inputstream to string
    if(inputStream != null)
        result = convertInputStreamToString(inputStream);
    else
        result = "Did not work!";


    System.out.print(result);

}catch (Exception e){

    e.printStackTrace();
}