【问题标题】:Read JSON from PHP with cookie使用 cookie 从 PHP 读取 JSON
【发布时间】:2018-11-23 21:42:38
【问题描述】:

我正在为使用 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 值?

【问题讨论】:

标签: java php android cookies


【解决方案1】:

我想我找到了问题...这是我现在从服务器获取 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。

【讨论】:

    【解决方案2】:
    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();
    

    【讨论】:

    • 我如何在我的代码中实现它?我试过了,但它不起作用。它说'无法解析方法“getInstance”'
    • 你能把错误信息贴出来吗,检查logcat
    • \MainActivity.java:159: 错误:找不到符号 CookieManager cookieManager = CookieManager.getInstance(); ^ 符号:方法 getInstance() 位置:类 CookieManager \MainActivity.java:160:错误:找不到符号 String cookieString = cookieManager.getCookie(SystemConstants.URL_COOKIE); ^ 符号:变量 SystemConstants 位置:类 MainActivity 2 错误您是说这个吗?
    • 我猜你使用了错误的导入,你能检查一下你是否从正确的包中导入了 InputManager,那不是错误,它只是编译错误,因为你的 IDE 找不到引用。
    • 我更改了导入包,现在 getInstance 可以工作了。只有 SystemConstants 无法解析。我和那有什么关系?
    猜你喜欢
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 2013-11-10
    • 2014-04-19
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    相关资源
    最近更新 更多