2016-11-04 5 views
0

私はNodeJSバックエンドサーバでAndroidアプリを開発しています。ユーザーがログインした後に別のページにリクエストがあったときにユーザーを認証する際に問題が発生しています。req.userはAndroidアプリからNodeJSサーバへのリクエストでは未定義です

ログインすると、set-cookieの値がSharedPrefsに格納されます。 POSTリクエストを行うと、req.user.authenticateを使用して、バックエンドでユーザーを認証するために、という値をヘッダーに送信します。つまり、con.setRequestProperty("set-cookie", cookie);です。

ただし、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); 

答えて

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

がDefaultHttpClient(ないこの形式でデータを送信します)は廃止予定? – user782400

+0

HttpURLConnectionを使用すると、json形式でデータを送信することが重要になります。しかし、それを文字列 – siddhesh

+0

に変換する前にそれを変換する前に、あなたがHttpURLConnectionを使って動作させようとする答え – siddhesh

関連する問題