0

I want to get JSON from web service using POST method. This is my code, which I've tried:

public class Test {

public static void main(String[] args) {

    String urlStr = "http://dev.crnobelo.mk/web_services/index.php/index/horoscope";
    String[] paramName = { "horoscope_sign" };
    String[] paramVal = { "oven" };

    try {

        String output = httpPost(urlStr, paramName, paramVal);
        System.out.println("Result: " + output);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

public static String httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {

    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.connect();

    // Create the form content
    OutputStream out = conn.getOutputStream();
    Writer writer = new OutputStreamWriter(out, "UTF-8");

    for (int i = 0; i < paramName.length; i++) {
        writer.write(paramName[i]);
        writer.write("=");
        writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
    //  writer.write("&");
    }

    writer.close();
    out.close();

    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new IOException(conn.getResponseMessage());
    }

    // Buffer the result into a string
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;

    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }

    rd.close();

    conn.disconnect();

    return sb.toString();
    }
}

So, as result I should get JSON text, but i don't get anything, also no errors. Is my code wrong, or this service is not working, or something else...?

KiKo
  • 1,478
  • 7
  • 23
  • 54
  • Did you try to set `conn.setDoInput(true);` – iTech Sep 16 '14 at 18:45
  • I added, but again the same....blank result :/ – KiKo Sep 16 '14 at 18:50
  • 1
    Don't you need to do a `conn.connect();` at some point? Specifically, after you set all of your connection parameters, but before you request the input stream – user3062946 Sep 16 '14 at 18:53
  • Seems your server returns blank page. I tested it with RESTClient (Firefox plugin) and it returns blank – iTech Sep 16 '14 at 18:54
  • @iTech Perhaps you're not invoking the webservice with correct POST variables. – Gary Drocella Sep 16 '14 at 18:55
  • @user3062946 added, still empty. – KiKo Sep 16 '14 at 18:56
  • You need to test your server with different tool to make sure that it returns something, because for me it seems that the server just respond with blank page when passing the arguments you use in your code – iTech Sep 16 '14 at 18:57
  • @GaryDrocella Variable is horoscope_sign and the values are oven, bik, rak ... etc – KiKo Sep 16 '14 at 18:57
  • @iTech maybe the server is not working... – KiKo Sep 16 '14 at 19:02
  • possible duplicate of [How to use java.net.URLConnection to fire and handle HTTP requests?](http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests) – Gary Drocella Sep 16 '14 at 19:16

1 Answers1

0

I would always recommend using gson. This will simplify your life because, with a single line you can parse your JSON and store it in a Object EJ:

{
  "key_1" : "name",
  "key_2" : "last_name",
  "friends" : [
    "jhon", "devorah", "charles"
  ]
}

And the class attributes beeing something like this

public class User {
  public String key_1;
  public String last_name;
  ArrayList<String> friends; 
}

Then, the reponse you are getting would be parse like this:

User u = new GsonBuilder.create().fromJson(httpResponseFromServer, User.class);

And there you go, a fully populated object with your Json data.

This code belongs to my utils.java wich i add to every project of mine. This would give you the response from an http server. Hope it helps.

public static String getStrResponse(String url, List<NameValuePair> params) {
        try {

            HttpClient httpclient = createHttpClient();
            HttpPost httppost = new HttpPost(url);

            List<NameValuePair> nameValuePairs = params;

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            InputStream in = entity.getContent();

            BufferedReader bReader = new BufferedReader(new InputStreamReader(
                    in));

            StringBuffer str = new StringBuffer();
            String line = null;

            while ((line = bReader.readLine()) != null) {
                str.append(line);
            }

            return str.toString();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "FALSE";
    }

To use it, simply like this.

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("mensaje", message));
nameValuePairs.add(new BasicNameValuePair("id_from", id_from));
nameValuePairs.add(new BasicNameValuePair("id_to", id_to));
Log.v("RESPONSE", utils.getStrResponse(yourUrl, nameValuePairs));

If the problem persits and you still get an empty response you should probably check your server side code or the conecction.

  • 2
    gson is a good recommendation, but this doesn't really answer his question at hand. – Gary Drocella Sep 16 '14 at 19:01
  • I think his primary issue is the fact that the server isn't responding with the JSON response that he expects. I don't think he's even really asking for help on parsing the JSON response (that he isn't getting) – user3062946 Sep 16 '14 at 19:02
  • In that case he should have asked how to create a json object on server side not "I want to get JSON from web service using POST method." Ive edited my answer to provide a most complete, client side, solution. – Santiago Nicolas Roca Sep 16 '14 at 19:04
  • Yeah, as they said, I have problem probably with server or sending post req to server, not with parsing data – KiKo Sep 16 '14 at 19:05
  • It would help if you can add your server side code. Try using getStrResponse method ive provided. I know it works. If answer still empty the error must be somewhere else. – Santiago Nicolas Roca Sep 16 '14 at 19:07
  • How this answers the question? Also, using `HttpURLConnection` as per the OP's code is more recommended for Gingerbread and later than `HttpClient` as per your answer – iTech Sep 16 '14 at 20:19