【发布时间】:2018-10-20 05:01:03
【问题描述】:
我有一个 Android 应用程序,一旦按下按钮,就会向我服务器上的 .php 文件发送一个 HTTPRequest。在 HTTPRequest 中,我存储了在服务器端处理的 POST 变量。
这是我的代码:
public void sendRequest(Context context, String url, final HashMap<String, String> hm) {
RequestQueue queue = Volley.newRequestQueue(context);
Log.w("url", url);
// Request a string response from the provided URL.
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.w("Response", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.w("Sending progress", "Failure");
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
return new JSONObject(hm).toString().getBytes();
}
@Override
protected Map<String, String> getParams()
{
return hm;
}
};
// Add the request to the RequestQueue.
queue.add(sr);
}
请注意,使用的 HashMap 变量被传递到方法本身,因为我想在不同的其他类中动态使用此方法。数据正常,但存在一些明显的问题:
1) 出于某种原因,我的 JSON 字符串作为“键”而不是“值”传输。实际上我刚才问了一个关于这个的问题——有人很好地回答了我——你可以在POST data in PHP formatting issue看到这个问题。有没有办法解决这个问题?
2) 奇怪的是,当我的数据到达 PHP 时,所有的“”和“.”字符被替换为“_”。我怀疑其他敏感字符会相同,例如“/”和“'”。我知道这是否是一个 GET 变量,但是对于 POST 变量,这是否仍然会发生?还是这与(1)有关?
---编辑---
我传递给sendRequest方法的HashMap是动态生成的,但一般来说只是:
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("personName", ((EditText) findViewById(R.id.text1).getText().toString().trim());
hm.put("personNumber", ((EditText) findViewById(R.id.text2).getText().toString().trim());
sendRequest(getApplicationContext(), "http://foo.com/bar.php", hm);
数据可以到达那里,只是格式很奇怪,它确实对我在服务器端的处理产生了影响。
【问题讨论】:
-
显示你传递给服务器的 hashmap
标签: php android post android-volley