-1

Kindly don't confuse my question with sending body with POST request using HttpURLConnection.

I want to send body with GET request using HttpURLConnection. Here is code i am using.

public static String makeGETRequest(String endpoint, String encodedBody) {
    String responseJSON = null;
    URL url;
    HttpURLConnection connection;

    try {
        url = new URL(endpoint);
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.connect();
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(encodedBody.getBytes());
        outputStream.flush();

        Util.log(connection,connection.getResponseCode()+":"+connection.getRequestMethod());

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String responseChunk = null;
        responseJSON = "";
        while ((responseChunk = bufferedReader.readLine()) != null) {
            responseJSON += responseChunk;
        }

        bufferedReader.close();
        connection.disconnect();

    } catch (Exception e) {
        e.printStackTrace();
        Util.log(e, e.getMessage());
    }

    return responseJSON;
}

what happens is that the request type is identified automatically depending on the connection.getInputStream() and connection.getOutPutStream().

when you call connection.getOutPutStream() the request type is automatically set to POST even if you have explicitly set request type to GET using connection.setRequestMethod("GET").

The problem is that i am using 3rd party Web Service(API) which accepts request parameters as body with GET request

<get-request>
/myAPIEndPoint
body = parameter1=value as application/x-www-form-urlencoded

<response>
{json}

I am well aware that most of the case GET don't have request body but many of the web service often uses GET request with parameters as body instead of query string. Kindly guide me how i can send GET request with body in android without using any 3rd party library(OkHttp,Retrofit,Glide etc)

Azmat Karim Khan
  • 437
  • 5
  • 18
  • 1
    [`HttpURLConnection` does not support this](https://stackoverflow.com/a/18777986/115145), probably because [that sort of structure was somewhat out of spec back when Java was first created](https://stackoverflow.com/q/978061/115145). I am uncertain if any library supports this. You would need to open your own socket connection and manually communicate with the server. This may not be pleasant. – CommonsWare Jul 21 '19 at 21:39
  • 1
    For those reading this question who are willing to use libraries, it appears that [OkHttp does not support this either](https://github.com/square/okhttp/issues/2706), though you may be able to use the independent packaging of the Apache HttpClient library (see [this](https://github.com/elastic/elasticsearch/blob/8c40b2b54eac3e3ab3c41ece5c758be75173191b/client/rest/src/main/java/org/elasticsearch/client/HttpGetWithEntity.java)). – CommonsWare Jul 21 '19 at 21:48
  • Please use libraries – Artem Ptushkin Jul 21 '19 at 22:05
  • HTTP GET with body is not supported, and the reason for that is that is idempotent which means calling this method several times should not have any side effects. So please don't go against the standards. Use a method which support request body. – Hasasn Jul 21 '19 at 23:55

1 Answers1

0

use this code you will need to do a little modification but it will get the job done.

package com.kundan.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class GetWithBody {

    public static final String TYPE = "GET ";
    public static final String HTTP_VERSION = " HTTP/1.1";
    public static final String LINE_END = "\r\n";

    public static void main(String[] args) throws Exception {
        Socket socket = new Socket("localhost", 8080); // hostname and port default is 80
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write((TYPE + "<Resource Address>" + HTTP_VERSION + LINE_END).getBytes());// 
        outputStream.write(("User-Agent: Java Socket" + LINE_END).getBytes());
        outputStream.write(("Content-Type: application/x-www-form-urlencoded" + LINE_END).getBytes());
        outputStream.write(LINE_END.getBytes()); //end of headers
        outputStream.write(("parameter1=value&parameter2=value2" + LINE_END).getBytes()); //body 
        outputStream.flush();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String read = null;
        while ((read = bufferedReader.readLine()) != null) {
            builder.append(read);
        }

        String result = builder.toString();
        System.out.println(result);
    }
}

this the Raw HTTP Request Dump

GET <Resource Address> HTTP/1.1
User-Agent: Java Socket
Content-Type: application/x-www-form-urlencoded

parameter1=value&parameter2=value2

Note : This is for http request if you want https Connection Please refer to the link SSLSocketClient

Kundan Singh
  • 91
  • 1
  • 6