Send JSON from Java to PHP through Post

后端 未结 1 1440
孤独总比滥情好
孤独总比滥情好 2020-12-30 17:06

I am doing an Android program that is supposed to send data from the tablet to a PHP Web Service. The code for sending the JSON:

package com.example.shvalida         


        
相关标签:
1条回答
  • 2020-12-30 17:33

    From the comments section, it appears you only want the JSON being sent to your PHP script. Normally, you post POST this to PHP, and extract it:

    <?php
        print_r($_POST);
        $json_string = $_POST['message']; 
        $json = json_decode($json_string);
        print_r($json);
    ?>
    

    And then a small client example:

    public static void main(String[] args) {
    
        String json = "{\"message\":\"This is a message\"}";
    
        HttpClient httpClient = new DefaultHttpClient();
    
        try {
            HttpPost request = new HttpPost("http://somesite.com/test.php");
            StringEntity params =new StringEntity("message=" + json);
            request.addHeader("content-type", "application/x-www-form-urlencoded");
            request.setEntity(params);
            HttpResponse response = httpClient.execute(request);
    
            // handle response here...
    
            System.out.println(org.apache.http.util.EntityUtils.toString(response.getEntity()));
            org.apache.http.util.EntityUtils.consume(response.getEntity());
        } catch (Exception ex) {
            // handle exception here
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
    

    The output of this is:

    Array
    (
        [message] => {"message":"This is a message"}
    )
    stdClass Object
    (
        [message] => This is a message
    )
    
    0 讨论(0)
提交回复
热议问题