[英]Send data (POST or GET) to server with Volley Lib in Android
我开发了一个应用程序,我将通过Json
将数据从手机发送到服务器,为此我使用 Android 中的Volley
库。
但我无法向服务器发送数据!
我的简单 php 代码:
$name = $_GET["name"];
$j = array('name' =>$name);
echo json_encode($j);
我的Java代码:
private void makeJsonObjectRequest() {
mRequestQueue = Volley.newRequestQueue(this);
String url = "http://my-site-name/sampleGET.php";
StringRequest jsonObjReq = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("result:", response);
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("err", "Error: " + error.getMessage());
makeJsonObjectRequest();
}
}
){
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", "json");
return params;
}
};
mRequestQueue.add(jsonObjReq);
}
它也从下面的链接得到了帮助: 点击查看链接
但仍然无法使用它并将数据(POST 或 GET)从手机发送到服务器!!!
我怎样才能做到这一点?
正如关于如何将 json 从 android 发送到 php 的建议?
从当前代码中,删除此方法:
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", "json");
return params;
}
并重写getBody()
方法。 然后,根据以下示例对其进行调整以返回您需要的 json 数据作为请求正文:
public byte[] getBody() throws AuthFailureError {
JSONObject js = new JSONObject();
try {
js.put("fieldName", "fieldValue");
} catch (JSONException e) {
e.printStackTrace();
}
return js.toString().getBytes();
}
然后在 php 中解码你的 json 数据:
$jsonRequest = json_decode(stream_get_contents(STDIN));
var_dump($jsonRequest);
如果需要更多信息,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.