0

I am trying to access a page where I am sending a chunk of data using POST....at first it was doing well and posting the data and I was able to insert the data properly to my external db. All of a sudden, its failing to do proper request and I am getting status code of 400 in my Log. The procedure I am following is below.

    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        Log.e("URL", "> " + url);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
          throw new IOException("Post" + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
  }

when I check the status I get java.io.IOException with status code of 400. Please let me know where am I doing wrong. N.B:- When I manually enter the value to the page through browser, it works well. Does it have anything to do with encoding of data.

Saty
  • 2,355
  • 3
  • 31
  • 81
  • Encoding very well might be the issue. I would take a look at http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests – Anid Monsur Feb 10 '14 at 04:51
  • @ginovva320 I dont know if this was the issue or not however I just add www to my url and its starts working fine now. Previously my url was http://xxx.in/register I made it to http://www.xxx.in/register, its working now. Thanks for the effort. – Saty Feb 10 '14 at 06:28

0 Answers0