java - 使用 cookie 从 PHP 读取 JSON
问题描述
我正在为使用 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();
推荐阅读
- flutter - FileSystemException:无法打开文件,路径 = 'storage/emulated/0/DCIM/docs/myPdf.pdf'(操作系统错误:不允许操作,errno = 1)
- sql - 我如何选择所有从未做过跑步和游泳的举重运动员?
- android - 无法加载脚本:“确保您正在运行 Metro Server(运行'react-native start')”问题
- android - 每当点击被触发时如何随机播放列表
- http - 通过 HTTP(s) 发送 sql 命令(和接收选定数据)的缺点
- python - Python:如何从元组创建嵌套字典?
- xpath - Windows 任务计划程序 XPath 用于在一天中的某个小时过滤事件
- node.js - Loopback 3 在 EJS 视图中加载引导 CDN
- python - 将 Prophet 或 Auto ARIMA 与 Ray 结合使用
- javascript - 我在 html 中提取当前日期和时间的方式有问题吗?