Mysql 如何通过HttpClient在POST请求中将JSON数据作为主体发送

Mysql 如何通过HttpClient在POST请求中将JSON数据作为主体发送,mysql,json,rest,apache-httpclient-4.x,Mysql,Json,Rest,Apache Httpclient 4.x,我有一个要求。我有一个工作岗位电话(“http://localhost:8080/POSTAPI/table/testmaster/create)。我通过邮递员发送了JSON数据,并将详细信息插入MySQL数据库。现在我正试图通过apachehttpcleint发送json数据。但是,它无法插入到mysql数据库中 CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost("htt

我有一个要求。我有一个工作岗位电话
(“http://localhost:8080/POSTAPI/table/testmaster/create)
。我通过邮递员发送了
JSON
数据,并将详细信息插入MySQL数据库。现在我正试图通过apachehttpcleint发送
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或任何其他替代方案进行后期操作有任何想法,请让我知道。提前感谢。

使用以下代码:

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);
    }

}
私有类postJsonData扩展异步任务{
进程对话;
字符串responseString=null;
私有postJsonData(){
超级();
dialog=新建ProgressDialog(MainActivity.this);
this.dialog.setTitle(“请稍候”);
this.dialog.setCancelable(false);
this.dialog.show();
}
@凌驾
受保护的void onPreExecute(){
对话框。设置进度(0);
super.onPreExecute();
}
@凌驾
受保护的void onProgressUpdate(整数…进度){
//使进度条可见
if(this.dialog.isShowing()){
dialog.setProgress(progress[0]);
}
}
@抑制警告(“弃用”)
@凌驾
受保护的布尔doInBackground(Void…params){
布尔结果=假;
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://192.168.2.2/android/jsonpost.php");
试一试{
JSONObject testmaster=新的JSONObject();
试一试{
testmaster.put(“testRunId”,“1”);
testmaster.put(“testClassName”、“className”);
put(“testMethod”、“methodName”);
testmaster.put(“createdBy”、“leela”);
testmaster.put(“createdDate”、“startDate”);
}捕获(JSONException e){
e、 printStackTrace();
}
List nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“json_字符串”,testmaster.toString());
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
//进行服务器呼叫
HttpResponse response=httpclient.execute(httppost);
HttpEntity r_entity=response.getEntity();
int statusCode=response.getStatusLine().getStatusCode();
如果(状态代码==200){
//服务器响应
responseString=EntityUtils.toString(r_实体);
结果=假;
}否则{
responseString=“发生错误!Http状态代码:”
+状态码;
结果=假;
}
}捕获(最终客户协议例外e){
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
Toast.makeText(getApplicationContext(),
“ClientProtocolException:”+e.toString(),
吐司长度(长)
.show();
}
});
结果=假;
}捕获(最终IOE例外){
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
Toast.makeText(getApplicationContext(),
“IOException:”+e.toString(),
吐司长度(长)
.show();
}
});
结果=假;
}
返回结果;
}
@凌驾
受保护的void onPostExecute(最终布尔值成功){
//progressBar.setVisibility(View.GONE);
if(dialog.isShowing()){
dialog.dismise();
}
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
Toast.makeText(getApplicationContext(),
“来自服务器的响应:”+responseString,
吐司长度(长)
.show();
}
});
如果(成功){
}否则{
}
super.onPostExecute(成功);
}
}
下面是我的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);
?>

可能的副本实际上不起作用。