【问题标题】:How to get json object from android to php如何从android获取json对象到php
【发布时间】:2013-05-03 02:40:36
【问题描述】:

我正在尝试为我的 android 应用程序构建 Web 服务。 但我在将参数发送到 php 时遇到问题。 我正在使用这些代码块来 Http-Post。

    public String requestJson(String method, JSONObject parameters) {
        try {
            int TIMEOUT_MILLISEC = 10000; 
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
            HttpClient client = new DefaultHttpClient(httpParams);

            String tmpUrl = serviceUrl.trim() + (serviceUrl.trim().endsWith("/") ? method : "/" + method);

            HttpPost request = new HttpPost(tmpUrl);

            request.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8");

            if (parameters != null)
            {
                request.setEntity(new StringEntity(parameters.toString(), HTTP.UTF_8));
            }

            HttpResponse response = client.execute(request);

            final int statusCode = response.getStatusLine().getStatusCode();
            final String jsonResponse = EntityUtils.toString(response.getEntity());

            if (statusCode != HttpStatus.SC_OK) {
                Log.w(TAG, "Error in web request: " + statusCode);
                Log.w(TAG, jsonResponse);
                return null;
            } else {
                Log.i(TAG, jsonResponse);
                return jsonResponse;
            }
        } catch (Exception e) {
            Log.e(TAG, "Error in fetching JSON due to -> " + e.toString());
        }
        return null;
    }


    public String testFunction() {
        try {
            JSONObject param = new JSONObject();
            param.put("testID", 123);
            JsonCevabi = requestJson("test.php", param);

            if (JsonCevabi != null) {
                JSONObject jo = new JSONObject(JsonCevabi);
                JSONArray ja = new JSONArray(jo.getString("d"));

                @SuppressWarnings("unchecked")
                List<SampleEntity> resultList = (List<SampleEntity>) new Gson().fromJson(ja.toString(), new TypeToken<List<SampleEntity>>() {
                }.getType());
                return JsonCevabi;
            }
            else
                return null;
        } catch (Exception e) {
            return null;
        }
    }

我的php代码是这样的;

<?php

$id = json_decode($_POST['testID']);


$json = "{d:[{sample1:'".$id."',sample2:'value12'}]}";
$response = $_GET["callback"] . $json;
echo $response;
?>

我想要做的是将 TestID 参数发送到 php。我正在努力让我回到这个值。

但我得到 {d:[{sample1:'',sample2:'value12'}]}

我想要的是 {d:[{sample1:'123',sample2:'value12'}]}

我错过了什么?

编辑:我发现了类似的问题,但没有帮助; Android JSON HttpClient to send data to PHP server with HttpResponse

【问题讨论】:

    标签: php android http-post


    【解决方案1】:

    正如@chandresh_cool 所说,POST 参数存在问题。 您应该像这样编辑您的 StringEntity: new StringEntity("testID="+parameters.toString(), HTTP.UTF_8).

    然后在您的服务器中,$id 变量包含解​​码后的 JSON,所以您应该这样做:

    $id = json_decode($_POST['testID'], true);
    $json = "{d:[{sample1:'".$id['testID']."',sample2:'value12'}]}";
    

    【讨论】:

    • 我试过你说的。但没有运气。我一定做错了什么。
    【解决方案2】:

    看起来像

    $_POST['testID']
    

    是个问题。您确定使用 post 方法发送变量吗?

    【讨论】:

    • 我猜在 testFunction 中是这样的; JSONObject 参数 = 新 JSONObject(); param.put("testID", 123);
    【解决方案3】:

    将php代码更改为以下解决了我的问题。

    <?php
    $postdata = $HTTP_RAW_POST_DATA;
    $data = json_decode($postdata);
    $id = $data->testID;
    $json = "{d:[{sample1:'".$id."',sample2:'value12'}]}";
    $response = $_GET["callback"] . $json;
    echo $response;
    ?>
    

    http://fahmirahman.wordpress.com/2011/04/26/the-simplest-way-to-post-parameters-between-android-and-php/

    更详细的信息可以在上面的链接中找到。

    【讨论】:

    • 经过一番调查,我发现 $_POST 仅在内容类型为 application/x-www-form-urlencodedmultipart/form-data 时使用
    【解决方案4】:
    @Java Code to send data: 
    
    StringEntity entity = new StringEntity("jsonRequest="+data.toString(), HTTP.UTF_8);                
    httpPost.setEntity(entity);
    response = httpClient.execute(httpPost);
    HttpEntity entityPost = response.getEntity();
    result = EntityUtils.toString(entityPost);
    return result;
    
    @PHP code to receive data
    $jsonRequest = json_decode($_REQUEST['jsonRequest'], true);
    
    @check if the data is coming we can log the contents
    date_default_timezone_set('EST');
    
    ini_set("log_errors", 1);
    ini_set("error_log", "site.log");
    error_log( "Hello, errors!".print_r($jsonRequest[id],1) );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 2016-11-16
      相关资源
      最近更新 更多