doulong6761 2018-06-14 07:31
浏览 138

使用cookie从PHP读取JSON

I´m building an app for a existing website which uses JavaScript and PHP. Now I want to get JSON from PHP, but the PHP needs a cookie to give the correct value. The cookie is made while logging in to the website. I can't get it to work in my Java code. It reads the JSON from the PHP but the value is always 0 because it doesn't get the cookie.

The code I have to get the JSON value:

private void postPHP() throws IOException, JSONException {

    URL url = new URL("http://piggybank.wordmediavormgever.nl/getSaldo.php"); // URL to your application
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("rekeningnr", ""); // All parameters, also easy

    StringBuilder postData = new StringBuilder();
    // POST as urlencoded is basically key-value pairs, as with GET
    // This creates key=value&key=value&... pairs
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }

    // Convert string to byte array, as it should be sent
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    // Connect, easy
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    // Tell server that this is POST and in which format is the data
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    // This gets the output from your server
    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    for (int c; (c = in.read()) >= 0;)
        System.out.print((char)c);
// Do something with http.getInputStream()

}

private void getData() throws IOException, JSONException {
    TextView txtUser = (TextView) findViewById(R.id.user);
    JSONObject json = readJsonFromUrl("http://piggybank.wordmediavormgever.nl/getSaldo.php");
    try {
        String response = json.getString("saldo");
        Log.e("saldo", response);
        response = json.getString("saldo");
        txtUser.setText(response);

    } catch (JSONException e) {

        e.printStackTrace();
    }
}

The code to login is:

private void checkLogin(final String user, final String pass) {
    // Tag used to cancel the request
    String tag_string_req = "req_login";

    pDialog.setMessage("Logging in ...");
    showDialog();

    StringRequest strReq = new StringRequest(Method.POST,
           AppConfig.URL_LOGIN , new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Login Response: " + response.toString());
            hideDialog();

            try {
                JSONObject jObj = new JSONObject(response);
                int login1 = jObj.getInt("howislife");
                System.out.println(login1);
                //Check for error node in json
                if (login1 == 1) {
                    // user successfully logged in
                    // Create login session
                    session.setLogin(true);


                    // Launch main activity
                    Intent intent = new Intent(LoginActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();
                } else if(login1 == 2) {
                    Toast.makeText(getApplicationContext(), "Wachtwoord verkeerd", Toast.LENGTH_LONG).show();
                } else if(login1 == 3) {
                    Toast.makeText(getApplicationContext(), "Gebruikersnaam of/en wachtwoord verkeerd", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Er is iets fout gegaan, probeer opnieuw.", Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
            }


        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Login Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("user", user);
            params.put("pass", pass);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

How can I get the cookie and use it to get the correct value from the getSaldo.php?

EDIT: Okay, I just found out you can create a cookie yourself, the website stores that cookie and remembers it for some time. That makes it a bit easier. So now my question is how can I send a cookie to the PHP so it stores it on the server and gives the correct JSON value?

  • 写回答

2条回答 默认 最新

  • duanaigua4033 2018-06-14 07:46
    关注
    CookieManager cookieManager = CookieManager.getInstance();
        String cookieString = cookieManager.getCookie(SystemConstants.URL_COOKIE); 
        URL url = new URL(urlToServer);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Cookie", cookieString);
        connection.connect();
        OutputStream out = connection.getOutputStream();
        out.write(data.getBytes());
        out.flush();
        out.close();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器