HttpClient和简单的JSON Http Post请求

时间:2014-12-07 16:37:48

标签: java json http request httpclient

我正在尝试使用Apache HttpClient和JSON-Simple 1.1从Java SE应用程序向Java EE应用程序发出HTTP Post请求。我相信我主要完成了请求,但很难搞清楚如何将JSON添加到它以及如何完成此请求。

我需要做些什么才能包含JSON以及完成此帖子请求还需要做些什么?

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

  }

}

}

0 个答案:

没有答案