如何通过 HttpClient 在 POST 请求中将 JSON 数据作为正文发送

Posted

技术标签:

【中文标题】如何通过 HttpClient 在 POST 请求中将 JSON 数据作为正文发送【英文标题】:How to send JSON data as body in POST request through HttpClient 【发布时间】:2016-11-03 01:28:36 【问题描述】:

我有一个要求。我有一个有效的 POST 电话 ("http://localhost:8080/POSTAPI/table/testmaster/create")。我通过邮递员发送了JSON 数据,并将详细信息插入到 mysql 数据库中。现在我正在尝试通过apache httpcleint 发送json 数据。但是,它无法插入mysql 数据库。

CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/POSTAPI/table/testmaster/create");
    JSONObject testmaster = new JSONObject();
    testmaster.put("testRunId", testRunId);
    testmaster.put("testClassName", className);
    testmaster.put("testMethod", methodName);
    testmaster.put("createdBy", "leela");
    testmaster.put("createdDate", startDate);
    testmaster.put("lastUpdatedBy", "raghu");
    testmaster.put("lastUpdatedDate", endDate);
    testmaster.put("attribute1", "methodName");
    testmaster.put("attribute1Value",methodName );
    testmaster.put("attribute2", "result");
    testmaster.put("attribute2Value", successResult);
    testmaster.put("attribute3", "Test Suite");
    testmaster.put("attribute3Value", suiteName);
    testmaster.put("attribute4", "test group");
    testmaster.put("attribute4Value", TestGroup);
    testmaster.put("attribute5", "dataprovider");
    testmaster.put("attribute5Value", dataProvider);

    StringEntity stringEntity = new StringEntity(testmaster.toString());
    post.setEntity(stringEntity);
    post.setHeader("Accept", "application/json");
    post.setHeader("Content-type", "application/json");
    CloseableHttpResponse response = client.execute(post);
    System.out.println("Status: "+response.getStatusLine());

这是我尝试过的。如果有人对通过 httpclient 或任何其他替代方法进行后期操作有任何想法,请告诉我。提前致谢。

【问题讨论】:

How to POST JSON request using Apache HttpClient?的可能重复 这实际上没有用。 【参考方案1】:

使用以下代码:

private class postJsonData extends AsyncTask<Void, Integer, Boolean> 

    ProgressDialog dialog;
    String responseString = null;

    private postJsonData() 
        super();
        dialog = new ProgressDialog(MainActivity.this);
        this.dialog.setTitle("Please wait.");            
        this.dialog.setCancelable(false);
        this.dialog.show();
    

    @Override
    protected void onPreExecute() 
        dialog.setProgress(0);
        super.onPreExecute();
    

    @Override
    protected void onProgressUpdate(Integer... progress) 
        // Making progress bar visible
        if (this.dialog.isShowing()) 
            dialog.setProgress(progress[0]);
        
    

    @SuppressWarnings("deprecation")
    @Override
    protected Boolean doInBackground(Void... params) 
        Boolean result=false;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.2.2/android/jsonpost.php");

        try 
            JSONObject testmaster = new JSONObject();

            try 
                testmaster.put("testRunId", "1");
                testmaster.put("testClassName", "className");
                testmaster.put("testMethod", "methodName");
                testmaster.put("createdBy", "leela");
                testmaster.put("createdDate", "startDate");
             catch (JSONException e) 
                e.printStackTrace();
            

            List<NameValuePair> nameValuePairs = new ArrayList<>();
            nameValuePairs.add(new BasicNameValuePair("json_string", testmaster.toString()));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) 
                // Server response
                responseString = EntityUtils.toString(r_entity);
                result = false;

             else 
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
                result = false;
            

         catch (final ClientProtocolException e) 
            runOnUiThread(new Runnable() 
                @Override
                public void run() 
                    Toast.makeText(getApplicationContext(),
                            "ClientProtocolException : " + e.toString(),
                            Toast.LENGTH_LONG)
                            .show();
                
            );
            result = false;
         catch (final IOException e) 
            runOnUiThread(new Runnable() 
                @Override
                public void run() 
                    Toast.makeText(getApplicationContext(),
                            "IOException : " + e.toString(),
                            Toast.LENGTH_LONG)
                            .show();
                
            );
            result = false;
        

        return result;
    

    @Override
    protected void onPostExecute(final Boolean success) 
        //progressBar.setVisibility(View.GONE);
        if (dialog.isShowing())
            dialog.dismiss();
        

        runOnUiThread(new Runnable() 
            @Override
            public void run() 
                Toast.makeText(getApplicationContext(),
                        "Response from Server: " + responseString ,
                        Toast.LENGTH_LONG)
                        .show();
            
        );

        if (success)

        else

        

        super.onPostExecute(success);
    


这是我的 php 代码,它接受 json 字符串并解码为数组。

<?php

if (empty($_POST['json_string'])) 
    echo "Empty json data"; 
    exit;
else
    $json_string = $_POST['json_string'];


$params = array();
$params = json_decode($json_string,true);
//echo $params['testClassName'];

var_dump($params);
?>

【讨论】:

以上是关于如何通过 HttpClient 在 POST 请求中将 JSON 数据作为正文发送的主要内容,如果未能解决你的问题,请参考以下文章

无法通过 HTTPClient 向 REST 发送 post 请求

取消 'HttpClient' POST 请求

C# HttpClient:如何在 POST 请求中发送查询字符串

如何在 Android 中使用 HTTPClient 以 JSON 格式发送 POST 请求?

httpclient能通过get类型请求发送json数据吗?

Android下通过HttpClient执行 HTTP POST 请求 的代码