HttpURLConnection - повторный запрос с базовой аутентификацией
Мое приложение должно отправлять много запросов в один и тот же домен для API REST с базовой аутентификацией.
Приведенный ниже код работает, но каждый раз ему нужны имя пользователя и пароль. Есть ли способ аутентификации только один раз, как в браузерах? (У меня такая же проблема в 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();
}
}
Спасибо.
Эта часть здесь, потому что мой вопрос был "в основном код" в противном случае.
1 ответ
Решение
Браузер работает на Cookies. Для этого вам нужно будет перехватить файлы cookie в ответе при входе в систему, сохранить их, а затем вы можете отправить их в своем запросе. Посмотрите ответ на этот ответ на stackru о том, как этого добиться