Пакет org.apache.http
осуждался на некоторое время из-за работы и других вопросов, и теперь полностью удалены, начиная с уровня API 23.
Вы должны использовать HttpURLConnection, который имеет хорошую документацию проведет Вас через весь процесс.
Если вам нужен код состояния, позвоните по номеру getResponseCode()
на экземпляр HttpURLConnection.
Вот пример кода:
@Nullable
public NetworkResponse openUrl(@NonNull String urlStr) {
URL url = new URL(urlStr);
// for secure connections, use this: HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String networkErrorStr;
try {
int responseCode = connection.getResponseCode();
InputStream er = connection.getErrorStream();
if (er != null) {
// if you get here, you'll anticipate an error, for example 404, 500, etc.
networkErrorStr = getResponse(er); // save the error message
}
InputStream is = connection.getInputStream(); // this will throw an exception if the previous getErrorStream() wasn't null
String responseStr = getResponse(is); // the actual response string on success
return new NetworkResponse(responseCode, responseStr);
} catch (Exception e) {
try {
if (connection != null) {
// you have to call it again because the connection is now set to error mode
int code = connection.getResponseCode();
return new NetworkResponse(code, networkErrorStr); // response on error
}
} catch (Exception e1) {
e1.printStackTrace(); // for debug purposes
}
e.printStackTrace(); // for debug purposes
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
private String getResponse(InputStream is) throws IOException {
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
public static class NetworkResponse { // it is static because you will use it inside a class probably
public NetworkResponse(int code, @Nullable String str) {
// do whatever you want with the data
}
}
Да, я использую HttpURLConnection, но если я хочу узнать код состояния для ответа сервера, какой код мне использовать? спасибо – Elgendy
Добавил образец кода к моему ответу. –
работает отлично, спасибо ^^ – Elgendy