0

Posting argument data from my form works perfectly but i need to post the same information using JSON. How can this be done. My form looks like this.

<form enctype="multipart/form-data" method="post" action="http://myrestfulservice.com/">
    <input type="text" name="name">
    <input type="text" name="email">
    <textarea name="about" rows="3"></textarea>
    <input name="file" type="file">
</form>

And my JSON string looks like this.

{
"name":"Josh U",
"email":"xxx@gmail.com",
"about":"Get rich programming or die tryna be something else",
"file":"@/home/josh/image.png"
}

I have tried using that JSON string but i get the following

Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 500
at com.ijoshluisaac.restful.client.RESTFulClientPostUsingJavaHTTPClientLibrary.main(RESTFulClientPostUsingJavaHTTPClientLibrary.java:35)

My JAVA codes looks like this

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

  public class RESTFulClientPostUsingJavaHTTPClientLibrary {

// JSON content to post
private static final String JSON_OBJECT = "{\"name\":\"Josh U\",\"email\":\"xxx@gmail.com\",\"about\":\"Get rich programming or die tryna be something else\",\"file\":\"/home/josh/image.png\"}";

//Web services URLs
private static final String URL_SR = "http://myrestfulservice.com/";

public static void main(String[] args) {

    try {
        URL url = new URL(URL_SR);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");


        OutputStream os = conn.getOutputStream();
        os.write(JSON_OBJECT.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Successfully Executed RESTFul POST .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

}

theyCallMeJun
  • 911
  • 1
  • 10
  • 21
  • I think this will help you (http://stackoverflow.com/questions/15481382/how-to-send-form-field-value-to-a-rest-service-using-json-or-ajax) – MadTech May 11 '13 at 09:46
  • Why are you posting JSON to the server when it clearly expects url encoded form data? – Perception May 11 '13 at 11:26

2 Answers2

0

I think you have to do 2 steps:

  1. First is to convert your form contents into JS object(hard step).
  2. Second convert your JS object into JSON format(easy step).

You just need to add more functionality to jQuery serializeArray to give us our required JS object:

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

Then use JSON.stringify function to convert the JS object into JSON format. You can find more info here

Community
  • 1
  • 1
ebram khalil
  • 8,252
  • 7
  • 42
  • 60
-1

Go for jquery (as it provides many out of box features like serilaize the form parametrs to json)and use below code

var frm = $(document.myform);
var data = JSON.stringify(frm.serializeArray());

 or

var data = $('#yourForm).serializeArray();

see http://api.jquery.com/serializeArray/

var url = 'YourURL';

$.ajax({
  url: url,
  dataType: 'json',
  data: data ,
  type: 'POST',
  success: function(data) {

  }
 });
M Sach
  • 33,416
  • 76
  • 221
  • 314