Android通过HttpClient向PHP服务端发送JSON请求的代码修正求助
解决Android HttpClient发送JSON到PHP服务端的匹配问题
我来帮你搞定这个问题!你的代码核心问题是Android端发送数据的格式和PHP端接收的方式不匹配——Android把JSON打包成了表单字段发送,但PHP却在读取原始的请求体内容,两边没对上。下面给你两种可行的修正方案,选一种就行:
方案一:修改Android代码,直接发送JSON格式请求体
这种方案更符合标准的JSON接口规范,把JSON直接作为请求体发送,同时设置正确的请求头:
class AsyncT extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://test1.intuitionsoftwares.com/paytm/name2.php"); try { JSONObject jsonobj = new JSONObject(); jsonobj.put("name", "Suraj"); jsonobj.put("age", "25"); // 直接将JSON字符串作为请求体,替换原来的表单形式 StringEntity entity = new StringEntity(jsonobj.toString(), "UTF-8"); // 设置正确的Content-Type,告诉服务端这是JSON数据 httppost.setHeader("Content-Type", "application/json"); httppost.setEntity(entity); Log.e("mainToPost", "mainToPost" + jsonobj.toString()); HttpResponse response = httpclient.execute(httppost); InputStream inputStream = response.getEntity().getContent(); InputStreamToStringExample str = new InputStreamToStringExample(); responseServer = str.getStringFromInputStream(inputStream); Log.e("response", "response -----" + responseServer); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); txt.setText(responseServer); } }
PHP端代码保持你原来的即可,这样就能正确从php://input读取到JSON数据了。
方案二:修改PHP代码,读取表单中的JSON字段
如果你不想改动Android端的发送逻辑,那只需要调整PHP端,读取POST表单里的req字段即可:
<?php header('Content-Type: application/json'); // 读取POST表单中的req字段,而不是原始请求体 $content = $_POST['req']; $get = json_decode($content); //Process the JSON. $name = $get->name; $age = $get->age; // 这里可以按需求输出,比如返回格式化的JSON或者直接拼接字符串 echo "Name: " . $name . ", Age: " . $age; // 或者返回JSON格式响应:echo json_encode(["name" => $name, "age" => $age]); ?>
测试提示
选其中一种方案修改后,运行Android应用,就能在你的TextView里看到服务端返回的内容了(比如原始逻辑下的Suraj25,或者你调整后的格式化文本)。
内容的提问来源于stack exchange,提问作者Game Of Thrones SuperFan
相关产品推荐
相关产品推荐

