gpt4 book ai didi

java - 使用 cookie 从 PHP 读取 JSON

转载 作者:行者123 更新时间:2023-12-02 11:07:33 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com