使用cookie

时间:2018-06-14 07:31:13

标签: java php android cookies

我正在为使用JavaScript和PHP的现有网站构建应用。现在我想从PHP获取JSON,但PHP需要一个cookie来提供正确的值。 cookie是在登录网站时制作的。我不能让它在我的Java代码中工作。它从PHP读取JSON但值始终为0,因为它没有获取cookie。

我必须得到JSON值的代码:

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

要登录的代码是:

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

如何获取cookie并使用它从getSaldo.php获取正确的值?

编辑:好的,我发现你可以自己创建一个cookie,网站存储该cookie并记住它一段时间。这使它更容易一些。所以现在我的问题是如何将PHP发送到PHP,以便将其存储在服务器上并提供正确的JSON值?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我想我发现了问题...这是我现在从服务器获取JSON值的代码:

private void postPHP (String cookie1) throws IOException, JSONException {

    CookieManager cookieManager = CookieManager.getInstance();
    String cookieString = cookieManager.getCookie(cookie1);
    URL url = new URL("http://piggybank.wordmediavormgever.nl/getSaldo.php");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("thatsallfolks", cookieString);
    connection.connect();
    OutputStream out = connection.getOutputStream();
    out.write(data);
    out.flush();
    out.close();
}

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

正如您所看到的那样,它只是使用getData部分来显示JSON值,它只是使postPHP部分变得简单。而且我不知道如何将它们组合在一起,因此它首先使用cookie发送请求,然后获取必须在TextView中显示的JSON响应。我认为这出了什么问题。现在它只是从URL中读取JSON而不发送cookie。