【问题标题】:How to connect PHP with JSON type header如何将 PHP 与 JSON 类型标头连接起来
【发布时间】:2020-10-11 22:46:21
【问题描述】:

这是我的 PHP 代码

<?php require_once '../includes/DbOperations.php'; $response = array(); 

if($_SERVER['REQUEST_METHOD']=='POST'){
    if(isset($_POST['username']) and isset($_POST['password']) and isset($_POST['email']))
    {
        //operate the data further 

        $db = new DbOperations(); 

        $result = $db->createUser($_POST['username'],$_POST['password'],$_POST['email']);
        if($result == 1){
            $response['error'] = false; 
            $response['message'] = "User registered successfully";
        }elseif($result == 2){
            $response['error'] = true; 
            $response['message'] = "Some error occurred please try again";          
        }elseif($result == 0){
            $response['error'] = true; 
            $response['message'] = "It seems you are already registered, please choose a different email and username";                     
        }

    }else{
        $response['error'] = true; 
        $response['message'] = "Required fields are missing";
    }
}else{
    $response['error'] = true; 
    $response['message'] = "Invalid Request";
}

echo json_encode($response);
?>

当我使用 JSON 类型标头时它不起作用

String jsonResult = null;
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("username", "33");
        jsonObject.put("password", "33");
        jsonObject.put("email", "33@gmail.com");

        jsonResult = jsonObject.toString();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    String HitURL = "http://192.xxx.xxx.xxx/Android/v1/registerUser.php";
    MediaType MEDIA_PlainMT = MediaType.parse("text/plain; charset=utf-8");
    Request request = new Request.Builder().url(HitURL).post(RequestBody.create(MEDIA_PlainMT, jsonResult)).build();

    OkHttpClient client = new OkHttpClient();
    try {
        TLSSocketFactory tlsSocketFactory=new TLSSocketFactory();
        if (tlsSocketFactory.getTrustManager()!=null) {
            client = new OkHttpClient.Builder()
                    .sslSocketFactory(tlsSocketFactory, tlsSocketFactory.getTrustManager())
                    .build();
        }
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(okhttp3.Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, final Response response) throws IOException {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } else {
                String HitResponse = response.body().string();
                Log.v("/CheckLog/", HitResponse);
            }
        }
    });

结果

{"error":true,"message":"Required fields are missing"}

【问题讨论】:

  • 请写下你的发送代码sn-ps
  • @ASHKARAN 我更新了我的帖子,我使用的代码被剪掉了

标签: php android json api


【解决方案1】:

您的服务器代码需要提交常规的 application/x-www-form-urlencoded 值(也称为常规 POST 表单提交),但您的客户端正在将您的数据编码为 application/json(JSON 对象)。应该是哪一个?客户端和服务器必须相互一致。

如果您想使用 JSON 作为数据编码标准,您的代码应如下所示:

<?php

require_once '../includes/DbOperations.php';
$response = array(); 

if($_SERVER['REQUEST_METHOD']=='POST'){
    $raw_input = file_get_contents('php://input');
    try {
      $input = json_decode($raw_input, TRUE, 512, JSON_THROW_ON_ERROR);
      if (isset($input['username']) and isset($input['password']) and isset($input['email']))
      {
          //operate the data further 

          $db = new DbOperations(); 

          $result = $db->createUser($input['username'],$input['password'],$input['email']);
          if($result == 1){
              $response['error'] = false; 
              $response['message'] = "User registered successfully";
          }elseif($result == 2){
              $response['error'] = true; 
              $response['message'] = "Some error occurred please try again";          
          }elseif($result == 0){
              $response['error'] = true; 
              $response['message'] = "It seems you are already registered, please choose a different email and username";                     
          }

      }else{
          $response['error'] = true; 
          $response['message'] = "Required fields are missing";
      }
  } catch (Exception $e) {
      $response['error'] = true; 
      $response['message'] = "Invalid Request: " . $e->getMessage();
  }
}else{
    $response['error'] = true; 
    $response['message'] = "Invalid Request";
}

echo json_encode($response);

【讨论】:

  • 我从你的回答中学到了一些东西,非常感谢你,但是当我使用你的代码时,它在第 10 行说错了,你能帮忙看看缺少什么吗? ,
    致命错误:未捕获的错误:不能使用 stdClass 类型的对象作为 C:\AllMyFiles\Featuring\Database\Program\Xampp\htdocs\Android\v1\registerUser.php 中的数组: 10 堆栈跟踪:在 10 行的 C:\AllMyFiles\Featuring\Database\Program\Xampp\htdocs\Android\v1\registerUser.php 中抛出 #0 {main}
  • 我忘记了 json_decode 默认为你提供对象。所以结果$input 值不能用$input['key'] 检索。我已将 json_decode $assoc 标志更改为 TRUE,现在应该可以正常工作了。或者,您可以改为通过$input-&gt;key 获得某个密钥。两者都应该工作。
  • 谢谢它现在正在工作,JSON 对象需要使用 $input->key,如果我将 JSON 对象转换为数组,我需要使用 $input['key'],谢谢您的时间:D
猜你喜欢
  • 2013-08-11
  • 2021-10-15
  • 2013-01-27
  • 2013-10-09
  • 1970-01-01
  • 2017-04-03
  • 2015-01-28
  • 1970-01-01
  • 2018-06-08
相关资源
最近更新 更多