0

I am attempting to make an HTTP Post Request from a Java SE application to a Java EE application using Apache HttpClient and JSON-Simple 1.1. I believe that I am mostly done with the request but am having difficulty figuring out how to add the JSON to it and how to complete this request.

What do I need to do to include the JSON and what else needs to be done to finish this post request?

//HTTP POST REQUEST USING APACHE HTTPCLIENT 3.3 & SIMPLE JSON 1.1

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public static void postRequestUsingApacheHttpClient() {

      try {
//#1 This instantiates httpclient to make the request.
DefaultHttpClient httpClient = new DefaultHttpClient();

//#2 This adds the url to the post data.
HttpPost postRequest = new HttpPost("http://localhost:8080/program");

//#3 Create the JSON object.
JSONObject reportObject = new JSONObject();
reportObject.put("student_id", myClass[c].getStudentElement(s).getStudentNumber());
reportObject.put("student_name", myClass[c].getStudentElement(s).getName());
reportObject.put("school_name", getSchoolName());
reportObject.put("instructor_name", getInstructorName());
reportObject.put("course_name", myClass[c].getClassName());
reportObject.put("absent_days",        
     String.valueOf(myClass[c].getStudentElement(s).getAbsences()));
reportObject.put("tardy_days",   
     String.valueOf(myClass[c].getStudentElement(s).getTardies()));
reportObject.put("total_grade",   
     String.valueOf(myClass[c].getStudentElement(s).getTotalGrade()));


StringEntity se = new StringEntity(reportObject.toString());


    if (response.getStatusLine().getStatusCode() != 201) {
        throw new RuntimeException("Failed : HTTP error code : "
            + response.getStatusLine().getStatusCode());
    }

    BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    httpClient.getConnectionManager().shutdown();

  } catch (MalformedURLException e) {

    e.printStackTrace();

  } catch (IOException e) {

    e.printStackTrace();

  }

}

}

Daron
  • 329
  • 1
  • 4
  • 24
  • You can find the answer in this thread: http://stackoverflow.com/questions/20740349/http-post-request-with-json-string-in-java! – Chazar Dec 07 '14 at 17:12
  • I'm looking for an example that uses JSON Simple 1.1. And rather than completely scrap my own code and replace it with someone else's I'm looking for help in figuring out how to finish my own code. – Daron Dec 07 '14 at 18:21

0 Answers0