json Posts

How to Simulate JSon POST Request Using PHP and CURL

Basically, im trying to do a PHP POST request using JSon string as its format and able to consume JSon array string as responses. Dont forget to activate CURL in your php.ini file.

<?php

//set POST variables address and json string
$url = 'http://localhost:81/dudu.php';
$fields = array(
		'userName'=>'yyy@xxx.com',
		'password'=>'yyyy',
		'emailProvider'=>'xxxx'
                );
//{"userName":"yyy@xxx.com","password":"yyyy","emailProvider":"xxxx"}

//url-ify the data for the JSON POST
$fields_string = json_encode($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);

//execute post
$jsonResult = curl_exec($ch);

//close connection
curl_close($ch);

// [{"name":0,"email":"yyy@xxx.com"},{"name":1,"email":"yyy@xxx.com"},
// {"name":2,"email":"yyy@xxx.com"},{"name":3,"email":"yyy@xxx.com"}]
$results = json_decode($jsonResult, true);
foreach ( $results as $result )
{
    echo "name : {$result['name']} and email {$result['email']} <br />";
}

?>

This is what my browser will look like after im testing my JSon POST

Have fun with CURL :-)

Google+

How to Handle JSon POST Request Using PHP

On my last project, i need to create a php service using JSon to handle service requests from multiple clients. My PHP file would consume JSon string for its requests and produce JSon string as its responses.
Im not too familiar with PHP, but after sometime googling i’ve found a workaround. This is how i do it.

<?php
// JSon request format is : 
// {"userName":"654321@zzzz.com","password":"12345","emailProvider":"zzzz"}

// read JSon input
$data_back = json_decode(file_get_contents('php://input'));

// set json string to php variables
$userName = $data_back->{"userName"};
$password = $data_back->{"password"};
$emailProvider = $data_back->{"emailProvider"};

// create json response
$responses = array();
for ($i = 0; $i < 10; $i++) {
    $responses[] = array("name" => $i, "email" => $userName . " " . $password . " " . $emailProvider);
}

// JSon response format is : 
// [{"name":"eeee","email":"eee@zzzzz.com"},
// {"name":"aaaa","email":"aaaaa@zzzzz.com"},{"name":"cccc","email":"bbb@zzzzz.com"}]

// set header as json
header("Content-type: application/json");

// send response
echo json_encode($responses);
?>

This is the http header and body of request and response.

Hope it help others, have fun with JSon. ;-)

Google+

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();
            invoice.setBill(2000);
            invoice.setPo_number("2000");
            invoice.setUsername("edw");
            
            Gson g = new Gson();
            String json = g.toJson(invoice);
            
            System.out.println(json);

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

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

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 :)

Google+