Search code examples
javaandroidapiweb-servicesget

Send request body with GET request using HttpURLConnection in java


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)


Solution

  • 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