A Simple JSon Requestor using Java

In my latest project, i found the needed to simulate a json request from my local computer. After do some research, i created a simple java class to simulate json request to my servlet. Im using GSon to format my java class to json string, and Apache HttpComponents.

Im trying to do json request to my servlet, to do an invoice payment. First, as always, is an Incoice javabean.

package com.edw.bean;

 *  com.edw.bean.Invoice
 *  @author edw
public class Invoice {
    private String username;
    private String po_number;
    private int bill;

    // other setter and getter

and this is my main java class, it will do a simple Request to my servlet

package com.edw.json;

import com.edw.bean.Invoice;
import com.google.gson.Gson;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

 *  com.edw.json.JSonRequestor
 *  @author edw
public class JSonRequestor {

    public JSonRequestor() {

    private void doRequest() {
        URL serverURL = null;
        try {
            Invoice invoice = new Invoice();
            Gson g = new Gson();
            String json = g.toJson(invoice);

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://localhost:18000/EPay/CreateInvoice");
            StringEntity stringEntity = new StringEntity(json);
            System.out.println("executing request " + httppost.getRequestLine());
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
        } catch (Exception e) {

    public static void main(String[] args) {
        JSonRequestor jSonRequestor = new JSonRequestor();

and this is how my request will looks like

this is libraries that i used

I hope it would help others,
have fun and dont forget to visit Indonesia 🙂

No Comments

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked