【问题标题】:Android Posting JSON to PHPAndroid 将 JSON 发布到 PHP
【发布时间】:2015-07-14 18:48:50
【问题描述】:

我正在尝试将 JSON 后数组发送到 PHP 服务器。该数组包含 PHP 将解码的单独对象/票证。 Android 将数据从其本地数据库加载到 JSON 对象中就好了。我可以记录它提取的数据并在将其发送到 PHP 服务器之前查看它。在服务器端,数据不会成功。它正在发送一个空数组。

我的代码:

public void sendQueuedTickets() {
    // Check queue for tickets.
    if (dbc.checkQueTickets() != null) {
        String[] userInfo;
        Cursor cursor = dbc.checkQueTickets();
        int columns = cursor.getColumnCount();
        int rows = cursor.getCount();
        final ArrayList<Integer> queueIDs = new ArrayList<>();
        JSONArray arr = new JSONArray();
        cursor.moveToFirst();
        // Get user info.
        userInfo = dbc.checkCredentials();
        // Add user info and request type to params so server knows what we're doing.
        JSONObject jobj = new JSONObject();
        try {
            jobj.put("username", userInfo[0]);
            jobj.put("serverUserID", userInfo[2]);
            jobj.put("request", "submitTicket");
        } catch (JSONException e) { e.printStackTrace(); }
        // Add SQL tickets to params to be sent.
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < columns; c++) {
                try {
                    jobj.put(cursor.getColumnName(c), cursor.getString(c));
                } catch (JSONException e) { e.printStackTrace(); }
            }
            arr.put(jobj);
            queueIDs.add(cursor.getInt(0)); // id column value.
            cursor.moveToNext();
        }
        // Send ticket(s) to remote server.
        // Set timeout parameters.
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        // Continue with http request.
        HttpClient client = new DefaultHttpClient(httpParameters);
        HttpContext httpContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost("http://" + userInfo[3] + "." + dbc.REMOTE_SERVER_URL);
        try {
            StringEntity se = new StringEntity(arr.toString());
            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse response = client.execute(httpPost, httpContext);
            String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
            System.out.println(resFromServer);
            // Delete queued ticket(s) if sent transaction successful.
            if (resFromServer.contains("successfulSubmit")) {
                for (int r = 0; r < rows; r++) {
                    dbc.deleteQueTicket(queueIDs.get(r));
                }
            }
        } catch (Exception e) { e.printStackTrace(); }
    }
}

【问题讨论】:

  • 我们可以看看您是如何在服务器端捕获发送的数据的吗?
  • halfer,我设法丢失了我正在使用的原始代码。我确实知道我正在查看是否设置了 $_POST['json'] 不起作用。
  • @ChrisC。你的服务器端代码在哪里

标签: java php android json


【解决方案1】:

这是我在 PHP 服务器端用于从 Android 获取 JSON 数据的代码:

$json = file_get_contents('php://input');
$obj = json_decode($json,true);//true means convert to 2d array

这是我用于从 Android 发送的代码:

private void sendHttp(JSONArray json) throws JSONException, IOException

{
    HttpParams httpParams = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
    HttpConnectionParams.setSoTimeout(httpParams, 10000);

    HttpClient client = new DefaultHttpClient(httpParams);

    String url = "your url write it here";
    Log.i("","http post on url");
    HttpPost request = new HttpPost(url);//send an httppost to the string url as json format

    request.setEntity(new ByteArrayEntity(json.toString().getBytes(
            "UTF8")));

    request.setHeader("json", json.toString());
    request.setHeader("Accept", "application/json"); 
    request.setHeader("Content-Type", "application/json");
    Log.i("", "excuting request");
    HttpResponse response =client.execute(request);//getting response

    //getting the response
    HttpEntity entity = response.getEntity();
        InputStream is = null;
        StringBuilder sb=null;
        is=entity.getContent();
        BufferedReader reader = new BufferedReader(new       InputStreamReader(is,"iso-8859-1"),10);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line="0";

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();

        String result=sb.toString();
        JSONArray res=new JSONArray(result);//the response json array 

}

代码 100% 有效。

【讨论】:

  • 好答案!如您所知,我们希望答案在这里尽可能可读,因此,如果您可以不时使用Shift 键,它确实有助于:-)。如果您是从手机发帖,这里的普遍看法是它不是一个理想的发帖设备。
【解决方案2】:

我最终从here 找到了一个可行的解决方案。下面是最终代码:

public void sendQueuedTickets() {
    // Check queue for tickets.
    if (dbc.checkQueTickets() != null) {
        String[] userInfo;
        Cursor cursor = dbc.checkQueTickets();
        int columns = cursor.getColumnCount();
        int rows = cursor.getCount();
        final ArrayList<Integer> queueIDs = new ArrayList<>();
        JSONArray arr = new JSONArray();
        JSONObject jobj = new JSONObject();
        cursor.moveToFirst();
        // Get user info.
        userInfo = dbc.checkCredentials();
        // Add user info and request type to params so server knows what we're doing.
        try {
            jobj.put("username", userInfo[0]);
            jobj.put("serverUserID", userInfo[2]);
            jobj.put("request", "submitTicket");
        } catch (JSONException e) { e.printStackTrace(); }
        // Add SQL tickets to params to be sent.
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < columns; c++) {
                try {
                    jobj.put(cursor.getColumnName(c), cursor.getString(c));
                } catch (JSONException e) { e.printStackTrace(); }
            }
            arr.put(jobj);
            queueIDs.add(cursor.getInt(0)); // id column value.
            cursor.moveToNext();
        }

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        HttpClient client = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost("http://" + userInfo[3] + "." + dbc.REMOTE_SERVER_URL);
        httpPost.setHeader("json",arr.toString());
        httpPost.getParams().setParameter("jsonpost",arr);

        try {
            HttpResponse response = client.execute(httpPost);
            String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
            System.out.println(resFromServer);
            // Delete queued ticket(s) if sent transaction successful.
            if (resFromServer.contains("successfulSubmit")) {
                for (int r = 0; r < rows; r++) {
                    dbc.deleteQueTicket(queueIDs.get(r));
                }
            }
        } catch (Exception e) { e.printStackTrace(); }
    }
}

PHP服务器端代码是:

if (isset($_SERVER['HTTP_JSON']) {
    $json = $_SERVER['HTTP_JSON'];
    $data = json_decode($json, true);
    print_r($data);
}

这会将 JSON 票证数组打印为关联数组。

【讨论】:

  • PHP 看起来不正确。据我所知,服务器端变量HTTP_JSON 不是一个东西,所以我不知道它来自哪里。您要么想要获取特定的 $_POST['x'] 值,要么从 file_get_contents("php://input") 获取原始数据。
  • 我同意,halfer,但它有效。我很难找到有关 HTTP_JSON 的更多信息。我一直认为从发件人那里检索信息应该使用 $_POST 请求。
  • 嗯,奇怪。这是not documented,但如果它有效,它就有效。 php://input 方法不适合您吗?我想这对服务器更改会更有弹性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-21
相关资源
最近更新 更多