Android向PHP发布JSON

时间:2015-07-14 18:48:51

标签: java php android json

我正在尝试将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(); }
    }
}

2 个答案:

答案 0 :(得分: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%运行。

答案 1 :(得分:0)

我最终找到了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票证数组作为关联数组。