0

I have a android requirement of parsing the json content from url and have completed them, now i need to send back the results as json content back to the server url. Searched many previous posts, but most specify how to download and parse json content. Any inputs/examples of how to start off for posting contents to url in json would be of immense help!

Edit: Below is the sample code attached of what i am trying

try {

        URL url = new URL("http://localhost:8080/RESTfulExample/json/product/post");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        String input = "{\"qty\":100,\"name\":\"iPad 4\"}";

        OutputStream os = conn.getOutputStream();
        os.write(input.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("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

On executing this, getting connection refused, java.net.connect exception! Please help!!

bharath
  • 953
  • 4
  • 17
  • 30
  • You should consider adding how an example URL _should look_. – Siddharth Lele Mar 25 '13 at 04:17
  • Added the sample, please add ur views! – bharath Mar 25 '13 at 16:50
  • I expect that you have an actual url address where you put localhost? Did you try if the webservice properly responds at that address? (E.g. using cURL? Like this: `curl -d "param1=value1&param2=value2" http://yourURLhere:8080/?otherparam=othervalue` ) – Patrick Mar 25 '13 at 16:58

1 Answers1

1

You can use the below method for sending your JSON request.

public static HttpResponse sendRequest(String url, String request) throws Exception 
{
    //Create the httpclient to make request
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //create an HttpPost request object
    HttpPost httpost = new HttpPost(url);

    //Create the String entity to be passed to the HttpPost request
    StringEntity se = new StringEntity(request));

    //set the created StringEntity
    httpost.setEntity(se);

    //the intended
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");

    return httpclient.execute(httpost);
}

Hope this helps.

Abhishek Nandi
  • 4,265
  • 1
  • 30
  • 43