Alpesh003
Alpesh003

Reputation: 329

Server returned HTTP response code: 400 for URL HttpURLConnection.getInputStream for JSON POST data string

I'm trying to establish a HttpUrlConnection to a URL for its POST method and trying to POST JSON data in the request header. In doing so i'm getting the response code 400 for the URL with the below payload:

    {
       "classResolver":"EXTERNAL_DATA",
       "id":12345,
       "idEntity":"MUM",
       "nameEntity":"XYZ",
       "olympicIdEntity":null,
       "sidCreator":"X123",
       "nameCreator":"XXX, Test",
       "createTime":"15-Jul-2015 17:56:36 GMT +05:30",
       "modifyTime":"15-Jul-2015 17:56:36 GMT +05:30",
       "valueDate":"15-Jul-2015",
       "submissionCutoff":"15-Jul-2015 17:56:36 GMT +05:30",
       "alertId":null,
       "repairFlagRequired":false,
       "callbackRequiredFlag":false,
       "statementRefDebit":null,
       "thirdPartyApproval":null,
       "thirdPartyApprDetails":null,
       "thirdPartyReln":null,
       "adviceRefDebit":null,
       "idTcc":null,
       "accName":null,
       "isAcctTPRest":false,
       "idEntityDebitAcc":null
    }

The total JSON payload has around 250 elements with almost the same data.

The code is :

    URLConnection connection = null;
    connection = url.openConnection();
    connection.setRequestProperty("reqHeaderInfoJson", objectMapper.writeValueAsString(jsonObj));
    connection.setRequestProperty("Accept", mediaType);
    connection.setRequestProperty("Content-Type", mediaType);
    BufferedReader br=null;
    StringBuilder sb=null;
    InputStreamReader isr=null;
    try {
        isr=new InputStreamReader(connection.getInputStream(), "UTF-8");
        br = new BufferedReader(isr);
        sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
    } catch (Exception e) {
        logger.error("Number of header copied => headerCount=" + e.getStackTrace(),e);
        e.printStackTrace();
    }

The same works with any other JSON string. There is a definite problem with the JSON string that i'm passing. Can someone please suggest?

Upvotes: 0

Views: 7159

Answers (2)

Gonzalo GM
Gonzalo GM

Reputation: 99

if you just want to get JSON objects from server I leave the following code works for me without problems. I work with JSON objects stored nodes 1500

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
        List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(params,"UTF-8");
                encodedEntity.setContentEncoding(HTTP.UTF_8);
                httpPost.setEntity(encodedEntity);
                //httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        //codigo pruebna
        response = new Scanner(httpResponse.getEntity().getContent(),"UTF-8").useDelimiter("\\A").next();
        /*httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity,"utf-8");*/

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

    return response;

}

}

then you must use it as follows

// Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();
        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

Upvotes: 0

Gonzalo GM
Gonzalo GM

Reputation: 99

try adding the following to your code

connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();

then replaced

InputStreamReader isr = new InputStreamReader(...)

for

InputStream input =new BufferInputStream(url.openStream());

Upvotes: 0

Related Questions