2016-06-30 42 views
5

Ho un requisito. Ho una chiamata POST di lavoro ("http://localhost:8080/POSTAPI/table/testmaster/create"). Ho inviato i dati JSON tramite postino e i dettagli sono stati inseriti nel database MySQL. Ora sto cercando di inviare i dati json tramite apache httpcleint. ma, non è riuscito a inserire nel database mysql.Come inviare dati JSON come corpo nella richiesta POST tramite HttpClient

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

Questo è quello che ho provato. se qualcuno ha qualche idea di operazione post attraverso httpclient o qualsiasi altra alternativa per favore fatemelo sapere. Grazie in anticipo.

+0

Eventuali duplicati di [Come Inserisci richiesta JSON utilizzando Apache HttpClient?] (Http://stackoverflow.com/questions/12059278/how-to-post-json-request-using-apache-httpclient) – Set

+0

Quello non ha funzionato in realtà. – krish

risposta

0

utilizzare il seguente codice:

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

} 

Ecco il mio codice php che accetta la stringa JSON e decodificare in array.

<?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); 
?> 
Problemi correlati