0

I'm sending a POST Request using Java HttpURLConnection. I got 414 Response using the Approach 1

Approach 1 :

urlString = urlString + "?" + getParameters(params);

In Approach 1, I append the parameters to the URL. The parameter is very long and hence I got 414 Response Code.

So I tried the below approach.

Approach 2 :

In this approach I sent the parameters as form data. Now, the server does not receive the complete data or does not receive the data at all.

        URL url = new URL(urlString);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setAllowUserInteraction(true);
        connection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);

        if(headers != null) {
            Enumeration<String> enums = (Enumeration<String>)headers.propertyNames();
            while(enums.hasMoreElements()) {
                String key = enums.nextElement();
                String val = headers.getProperty(key);

                connection.setRequestProperty(key, val);
            }
        }           

        writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
        if(params != null) {
            Iterator it = params.keys();
            while(it.hasNext()) {
                String name = (String)it.next();
                String value = (String)params.get(name);
                value = URLDecoder.decode(value);
                System.out.println(" Param Name :: " + name + " - Value :: " + value);

                writer.append("--" + boundary).append(LINE_FEED);
                writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED);
                writer.append("Content-Type: text/plain; charset=UTF-8").append(LINE_FEED);
                writer.append(LINE_FEED);
                writer.append(value).append(LINE_FEED);
                writer.flush();
            }
        }           

        if(fileDetails != null) {
            File dataFile = (File)fileDetails.get("FILE");
            String fileName = fileDetails.optString("FILE_NAME","");

            writer.append("--" + boundary).append(LINE_FEED);
            writer.append("Content-Disposition: form-data; name=\"" + "FILE" + "\";filename=\"" + fileName + "\"").append(LINE_FEED);
            writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(dataFile.getName()));
            writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
            writer.append(LINE_FEED);
            writer.flush();

            fis = new FileInputStream(dataFile);
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while((bytesRead = fis.read(buffer)) != -1) {
                connection.getOutputStream().write(buffer, 0, bytesRead);
            }
            fis.close();

            writer.append(LINE_FEED); writer.flush();               
        }
        writer.append(LINE_FEED); writer.flush();
        writer.append("--" + boundary + "--").append(LINE_FEED); writer.close();

EDIT :

Curl Equivalent

curl https://api.domain.com?param1=param1val
-X POST
-H "Authorization: authtoken ba4604e8e433gfda92e360d51263oec5"
-H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8"
-F 'JSONStr="{
    "key1": "val1",
    "key2": "val2",
    "key3": "val3"
   }"

I'm trying to execute this curl command in Java.

How do I send large data in POST using Java ? I'm not going to send Files, just JSONObject as a String in the parameter value.

EDIT 2 :

I tried Apache HttpClient library

Here's the code.

        HttpPost httpPost = new HttpPost();
        if(headers != null) {
            Enumeration<String> enums = (Enumeration<String>)headers.propertyNames();
            while(enums.hasMoreElements()) {
                String key = enums.nextElement();
                String val = headers.getProperty(key);

                httpPost.addHeader(key, val);
            }
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            URI uri = new URI(urlString);
            httpPost.setURI(uri);

            if(params != null) {
                Iterator it = params.keys();
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                while(it.hasNext()) {
                    String paramName = (String)it.next();
                    String paramValue = (String)params.get(paramName);
                    paramValue = URLDecoder.decode(paramValue);

                    entity.addPart(paramName, new StringBody(paramValue, "text/plain", Charset.forName("UTF-8")));
                }
                httpPost.setEntity(entity);
            }

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse  httpresponse = httpClient.execute(httpPost);
            if(httpresponse.getEntity() != null) {
                StringBuilder sb = new StringBuilder();
                response = EntityUtils.toString(httpresponse.getEntity());
            }
        }

I tried the above code but the server does not receive the parameters.

Hulk Man
  • 153
  • 1
  • 15
  • 3
    You should not send any large strings as parameters. You should send them as post body. Then you can write to the Request Input Stream. The server will receive it. Also, if you are including anything in the URL string, it has to be appropriately escaped. THis is a good link. https://www.werockyourweb.com/url-escape-characters/ – horatius Jul 27 '18 at 14:29
  • How to send as post data? – Hulk Man Jul 27 '18 at 15:01
  • Check out this link. https://stackoverflow.com/questions/7181534/http-post-using-json-in-java – horatius Jul 27 '18 at 15:45
  • So, should I use a third party library? Can't this be done using native java httpurlconnection? – Hulk Man Jul 28 '18 at 00:50

0 Answers0