我想从客户端向服务器发送一条简单的消息(服务器不是localhost)。我使用Volley库和方法POST。 当我运行代码没有建立连接时,LogCat打印:
05-30 12:19:05.930: D/memalloc(12085): /dev/pmem: Mapped buffer base:0x51dec000 size:3727360 offset:3112960 fd:48
05-30 12:19:06.340: D/memalloc(12085): /dev/pmem: Mapped buffer base:0x5227a000 size:4382720 offset:3768320 fd:47
05-30 12:19:06.370: E/Volley(12085): [1] 2.onErrorResponse: Error:
客户代码:
String url = "http://myWebServer.eu";
RequestQueue queue;
JsonObjectRequest request;
Map<String, String> map = new HashMap<String, String>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue = Volley.newRequestQueue(this);
map.put("param1", "example");
request = new JsonObjectRequest(Request.Method.POST,
url,
new JSONObject(map),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(7));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
queue.add(request);
}
PHP服务器代码
$jsondata = $_POST['param1'];
$json = json_decode($jsondata,true);
echo $json ;
答案 0 :(得分:0)
在这里,您尝试将非json类型解码为json。 $ post [&#39; param1&#39;]是您可以从您的应用程序请求到服务器的字符串值只是打印$ post [&#39; param1&#39;]是字符串格式而不是json
$jsondata = $_POST['param1'];
echo $json_encode($_POST) ;
答案 1 :(得分:-1)
在你的php端写下面的代码:
$value = json_decode(file_get_contents('php://input'));
$json = $value->param1;
并且你应该将json格式发送回你的应用程序,正如你在这一行中看到的那样(public void onResponse(JSONObject response))
还会在帖子中添加标题:
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put( "charset", "utf-8");
return headers;
}