【问题标题】:HttpURLConnection - repeated request with basic authenticationHttpURLConnection - 具有基本身份验证的重复请求
【发布时间】:2018-02-10 20:17:22
【问题描述】:

我的应用需要向同一个域发出大量请求,以获得具有基本身份验证的 REST API。

下面的代码有效,但每次都需要用户名和密码。有没有办法像在浏览器中一样只进行一次身份验证? (我在桌面版的c#中有同样的问题)

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();
    }
}

谢谢。

这部分在这里是因为我的问题是“主要是代码”。

【问题讨论】:

    标签: java android rest httpurlconnection basic-authentication


    【解决方案1】:

    浏览器适用于 Cookie。为此,您需要拦截登录响应中的 cookie,将它们持久化,然后您可以在请求中发送它们。 Look at the answer on this stackoverflow answer on how to achieve it

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多