java - 使用 cookie 从 PHP 读取 JSON

标签 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 并记住它一段时间。这让它变得更容易一些。所以现在我的问题是如何将 cookie 发送到 PHP,以便将其存储在服务器上并给出正确的 JSON 值?

最佳答案

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

关于java - 使用 cookie 从 PHP 读取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50851951/

相关文章:

android - 如何在 Android NDK 中获取我的进程 ID (PID)?

java - 使用 for 循环设置 TextView 文本,以便显示多行

java - 收到此错误 "cannot access scala.reflect.api.TypeTags"

php - 带有 PHP 的 Gearman - worker 中的线程

php - 是否可以使用 DOMDocument 查询前 5 个图像?

php - rename() 和 unlink() 是异步函数吗?

android - Espresso : How to get the exact TextView from an LinearLayout?

java - 基线对齐的TextView裁剪多行文本的底行

java - 如何在jsp中以编程方式清除浏览器缓存?

java - 数组按 5's and 3' 计数,然后添加数组