Json not working with HttpPost probably around setEntity

前端 未结 1 979
不思量自难忘°
不思量自难忘° 2021-01-21 08:12

I am using this code to send this to my php file. The file looks what is coming like this.

file_put_contents(\'dump.txt\', \"POST: \\n\" . print_r($_POST, true)          


        
相关标签:
1条回答
  • 2021-01-21 08:53

    the way I send JSON with my DefaultHttpClient in my app work perfectly:

    public static HttpUriRequest createPostForJSONObject(
            JSONObject params, String url) {
        HttpPost post = new HttpPost(url);
        post.setEntity(createStringEntity(params));
        return post;
    }
    
    private static HttpEntity createStringEntity(JSONObject params) {
        StringEntity se = null;
        try {
            se = new StringEntity(params.toString(), "UTF-8");
            se.setContentType("application/json; charset=UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, "Failed to create StringEntity", e);
            exception = e;
        }
        return se;
    }
    

    in order to run this request in your code all you need to do is this:

    public void postData(String url,JSONObject json) {
        HttpClient httpclient = new DefaultHttpClient();
        try {
              HttpPost post = createPostForJSONObject(json, url);
              HttpResponse response = httpClient.execute(post);
              // DO YOUR THING
        } catch Exception {
             // HANDLE EXCEPTION
        }
    }
    
    0 讨论(0)
提交回复
热议问题