Android JSON to PHP Server and back

后端 未结 2 1931
悲&欢浪女
悲&欢浪女 2020-12-15 14:41

Can anybody offer a solution to the above?

For now, all i want to do is send a JSON request to my server (for example: {picture:jpg, color:green}), have the PHP acce

2条回答
  •  轮回少年
    2020-12-15 15:11

    OK, i've got the PHP. The below retrieves POST ed data and returns the service

    {'service'};
    
    print $service;
    
    ?>
    

    and the Android Code:

    in onCreate()

    path = "http://example.com/process/json.php";
    
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
                                                                                // Limit
        HttpResponse response;
        JSONObject json = new JSONObject();
        try {
            HttpPost post = new HttpPost(path);
            json.put("service", "GOOGLE");
            Log.i("jason Object", json.toString());
            post.setHeader("json", json.toString());
            StringEntity se = new StringEntity(json.toString());
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(se);
            response = client.execute(post);
            /* Checking response */
            if (response != null) {
                InputStream in = response.getEntity().getContent(); // Get the
                                                                    // data in
                                                                        // the
                                                                        // entity
                String a = convertStreamToString(in);
                Log.i("Read from Server", a);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    

    and where ever you want

    private static String convertStreamToString(InputStream is) {
    
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
    
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    

提交回复
热议问题