Android Posting JSON to PHP


Android Posting JSON to PHP

我试图将JSON post数组发送到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(); }
    }
}

这是我在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%正常

我最终从这里找到了一个有效的解决方案。下面是最终代码:

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票证数组。