我接着介绍了如何使用Volley发出HTTP请求(http://www.truiton.com/2015/02/android-volley-example/)的教程,一切顺利。我现在正在尝试发出POST请求但遇到问题的是我的POST数据没有被发送到服务器。
CustomJSONObjectRequest.java
package com.co.pa.ny;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class CustomJSONObjectRequest extends JsonObjectRequest {
public CustomJSONObjectRequest(int method,
String url,
JSONObject jsonRequest,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
@Override
public RetryPolicy getRetryPolicy() {
// here you can write a custom retry policy
return super.getRetryPolicy();
}
}
MainActivity.java
...
protected void onCreate(Bundle savedInstanceState) {
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
attemptLogin();
}
});
}
...
public void attemptLogin() {
String url = "http://example.com";
HashMap<String, String> params = new HashMap<String, String>();
params.put("email", emailField.getText().toString());
params.put("password", passwordField.getText().toString());
final CustomJSONObjectRequest jsonRequest = new CustomJSONObjectRequest(Request.Method.POST,
url,
new JSONObject(params),
this,
this);
jsonRequest.setTag(REQUEST_TAG);
mQueue.add(jsonRequest);
}
在服务器上,我正在使用:
进行非常简单的文件写入<?php
$file = 'newfile.txt';
$current = file_get_contents($file);
$current .= print_r($_POST, TRUE)."\n";
file_put_contents($file, $current);
点按应用程序中的按钮时,我的文本文件会附加一个简单的:
Array
(
)
一个告诉故事标志,即POST变量未被发送。我可以通过创建一个从浏览器POST到URL的简单表单来验证它是否有效。任何人都有任何想法,我想让我的POST请求在应用程序内正常工作吗?