grecof88
grecof88

Reputation: 87

HttpURLConnection - repeated request with basic authentication

My app needs to make a lot of requests to the same domain, for a REST API with basic authentication.

The code below works, but it needs username and password every time. Is there a way to authenticate only once like in browsers? (I have the same problem in c# for the desktop version)

public class RestRequest {

    public enum RestMethod {GET, POST}

    private String mUrl, mParams;
    private RestMethod mMethod;

    public RestRequest(RestMethod method, String url) {
        this(method, url, "");
    }

    public RestRequest(RestMethod method, String url, String params) {
        mUrl = url;
        mParams = (params != null) ? params : "";
        mMethod = method;
    }


    public RestResponse sendRequest(String authorization) throws IOException {
        HttpURLConnection connection = openConnection(authorization);
        if (mMethod == RestMethod.POST) {
            postParams(connection);
        }

        InputStream is = null;
        boolean error = false;
        int statusCode = HttpURLConnection.HTTP_ACCEPTED;

        try {
            is = connection.getInputStream();
        } catch (IOException e) {
            statusCode = getErrorCode(connection);
            is = connection.getErrorStream();
        }

        return new RestResponse(readStream(is), error, statusCode);
    }

    public RestRequest addParam(String name, String value) {
        if (mMethod == RestMethod.GET) {
            try {
                String encoded = URLEncoder.encode(value, StandardCharsets.UTF_8.name());
                mParams += name + "=" + encoded + "&";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return this;
    }

    //authorization is username:password
    private HttpURLConnection openConnection(String authorization) throws IOException {
        URLConnection connection;
        URL url;
        if (mMethod == RestMethod.GET)
            url = new URL(mUrl + "?" + mParams);
        else
            url = new URL(mUrl);

        connection = url.openConnection();
        String authStringEnc = Base64.encodeToString(authorization.getBytes(), Base64.NO_WRAP);
        connection.setRequestProperty("Authorization", "Basic " + authStringEnc);

        return (HttpsURLConnection) connection;
    }

    private void postParams(URLConnection connection) throws IOException {
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

        OutputStream output = connection.getOutputStream();
        output.write(mParams.getBytes());
    }

    private static int getErrorCode(HttpURLConnection conn) {
        int httpStatus;
        try {
            return conn.getResponseCode();
        } catch (IOException e) {
            return -1;
        }
    }

    private String readStream(InputStream is) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            if (is != null) {
                br = new BufferedReader(new InputStreamReader(is));
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}

Thank you.

This part is here because my question was "mostly code" otherwise.

Upvotes: 1

Views: 754

Answers (1)

karandeep singh
karandeep singh

Reputation: 2334

Browser works on Cookies. To achieve that, you will need to intercept the cookies in your login response, persist them and later you can send them in your request. Look at the answer on this stackoverflow answer on how to achieve it

Upvotes: 1

Related Questions