java.net.HttpURLConnection.getErrorStream()方法的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(9.6k)|赞(0)|评价(0)|浏览(738)

本文整理了Java中java.net.HttpURLConnection.getErrorStream()方法的一些代码示例,展示了HttpURLConnection.getErrorStream()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpURLConnection.getErrorStream()方法的具体详情如下:
包路径:java.net.HttpURLConnection
类名称:HttpURLConnection
方法名:getErrorStream

HttpURLConnection.getErrorStream介绍

[英]Returns an input stream from the server in the case of an error such as the requested file has not been found on the remote server. This stream can be used to read the data the server will send back.
[中]在远程服务器上未找到请求的文件等错误的情况下,从服务器返回输入流。此流可用于读取服务器将发回的数据。

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Override
public InputStream getBody() throws IOException {
  InputStream errorStream = this.connection.getErrorStream();
  this.responseStream = (errorStream != null ? errorStream : this.connection.getInputStream());
  return this.responseStream;
}

代码示例来源:origin: stackoverflow.com

HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
InputStream _is;
if (httpConn.getResponseCode() < 400) {
  _is = httpConn.getInputStream();
} else {
   /* error from server */
  _is = httpConn.getErrorStream();
}

代码示例来源:origin: Netflix/eureka

public static String readEc2MetadataUrl(MetaDataKey metaDataKey, URL url, int connectionTimeoutMs, int readTimeoutMs) throws IOException {
    HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    uc.setConnectTimeout(connectionTimeoutMs);
    uc.setReadTimeout(readTimeoutMs);
    uc.setRequestProperty("User-Agent", "eureka-java-client");

    if (uc.getResponseCode() != HttpURLConnection.HTTP_OK) {  // need to read the error for clean connection close
      BufferedReader br = new BufferedReader(new InputStreamReader(uc.getErrorStream()));
      try {
        while (br.readLine() != null) {
          // do nothing but keep reading the line
        }
      } finally {
        br.close();
      }
    } else {
      return metaDataKey.read(uc.getInputStream());
    }

    return null;
  }
}

代码示例来源:origin: cSploit/android

url = new URL(task.getUrl());
} catch (MalformedURLException e) {
 notifiers.execute(new Notifier(task, ("Bad URL: " + task.getUrl()).getBytes(), true));
 connection = url.openConnection();
 stream = connection.getInputStream();
} catch (IOException e) {
 if (connection != null && connection instanceof HttpURLConnection) {
  stream = ((HttpURLConnection) connection).getErrorStream();
  isError = true;
 } else {

代码示例来源:origin: testcontainers/testcontainers-java

private String getResponseBody(HttpURLConnection connection) throws IOException {
    BufferedReader reader;
    if (200 <= connection.getResponseCode() && connection.getResponseCode() <= 299) {
      reader = new BufferedReader(new InputStreamReader((connection.getInputStream())));
    } else {
      reader = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
    }

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
      builder.append(line);
    }
    return builder.toString();
  }
}

代码示例来源:origin: wildfly/wildfly

connection = openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setInstanceFollowRedirects(false);
try (InputStream inputStream = new BufferedInputStream(connection.getInputStream())) {
  JsonObject jsonObject = Json.createReader(inputStream).readObject();
  String accessToken = jsonObject.getString("access_token");
InputStream errorStream = null;
if (connection != null && connection.getErrorStream() != null) {
  errorStream = connection.getErrorStream();

代码示例来源:origin: javamelody/javamelody

public void post(ByteArrayOutputStream payload) throws IOException {
  final HttpURLConnection connection = (HttpURLConnection) openConnection();
  connection.setRequestMethod("POST");
  connection.setDoOutput(true);
  if (payload != null) {
    final OutputStream outputStream = connection.getOutputStream();
    payload.writeTo(outputStream);
    outputStream.flush();
  }
  final int status = connection.getResponseCode();
  if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
    final String error = InputOutput.pumpToString(connection.getErrorStream(),
        Charset.forName("UTF-8"));
    final String msg = "Error connecting to " + url + '(' + status + "): " + error;
    throw new IOException(msg);
  }
  connection.disconnect();
}

代码示例来源:origin: apache/flink

public static String getFromHTTP(String url, Time timeout) throws Exception {
  final URL u = new URL(url);
  LOG.info("Accessing URL " + url + " as URL: " + u);
  final long deadline = timeout.toMilliseconds() + System.currentTimeMillis();
  while (System.currentTimeMillis() <= deadline) {
    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
    connection.setConnectTimeout(100000);
    connection.connect();
    if (Objects.equals(HttpResponseStatus.SERVICE_UNAVAILABLE, HttpResponseStatus.valueOf(connection.getResponseCode()))) {
      // service not available --> Sleep and retry
      LOG.debug("Web service currently not available. Retrying the request in a bit.");
      Thread.sleep(100L);
    } else {
      InputStream is;
      if (connection.getResponseCode() >= 400) {
        // error!
        LOG.warn("HTTP Response code when connecting to {} was {}", url, connection.getResponseCode());
        is = connection.getErrorStream();
      } else {
        is = connection.getInputStream();
      }
      return IOUtils.toString(is, ConfigConstants.DEFAULT_CHARSET);
    }
  }
  throw new TimeoutException("Could not get HTTP response in time since the service is still unavailable.");
}

代码示例来源:origin: Alluxio/alluxio

@Override
public void close() throws IOException {
 mOutputStream.close();
 InputStream is = null;
 try {
  // Status 400 and up should be read from error stream.
  // Expecting here 201 Create or 202 Accepted.
  if (mHttpCon.getResponseCode() >= 400) {
   LOG.error("Failed to write data to Swift with error code: " + mHttpCon.getResponseCode());
   is = mHttpCon.getErrorStream();
  } else {
   is = mHttpCon.getInputStream();
  }
  is.close();
 } catch (Exception e) {
  LOG.error(e.getMessage());
  if (is != null) {
   is.close();
  }
 }
 mHttpCon.disconnect();
}

代码示例来源:origin: libgdx/libgdx

private InputStream getInputStream () {
    try {
      return connection.getInputStream();
    } catch (IOException e) {
      return connection.getErrorStream();
    }
  }
}

代码示例来源:origin: wildfly/wildfly

connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(params.length));
try (InputStream inputStream = new BufferedInputStream(connection.getInputStream())) {
  return Json.createReader(inputStream).readObject();
if (connection != null && connection.getErrorStream() != null) {
  InputStream errorStream = connection.getErrorStream();

代码示例来源:origin: prometheus/client_java

connection.setDoOutput(true);
connection.setRequestMethod(method);
 int response = connection.getResponseCode();
 if (response != HttpURLConnection.HTTP_ACCEPTED) {
  String errorMessage;
  InputStream errorStream = connection.getErrorStream();
  if(response >= 400 && errorStream != null) {
   String errBody = readFromStream(errorStream);

代码示例来源:origin: stackoverflow.com

HttpURLConnection httpConn = (HttpURLConnection)connection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
  is = httpConn.getErrorStream();
} else {
  is = httpConn.getInputStream();
}

代码示例来源:origin: alibaba/nacos

static public HttpResult invokeURL(String url, List<String> headers, String encoding) throws IOException {
  HttpURLConnection conn = null;
  try {
    conn = (HttpURLConnection)new URL(url).openConnection();
    conn.setRequestMethod("GET");
    int respCode = conn.getResponseCode();
    String resp = null;
      resp = IOUtils.toString(conn.getInputStream());
    } else {
      resp = IOUtils.toString(conn.getErrorStream());

代码示例来源:origin: alibaba/nacos

private static HttpResult getResult(HttpURLConnection conn) throws IOException {
  int respCode = conn.getResponseCode();
  InputStream inputStream;
  if (HttpURLConnection.HTTP_OK == respCode) {
    inputStream = conn.getInputStream();
  } else {
    inputStream = conn.getErrorStream();
  }
  Map<String, String> respHeaders = new HashMap<String, String>(conn.getHeaderFields().size());
  for (Map.Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
    respHeaders.put(entry.getKey(), entry.getValue().get(0));
  }
  String gzipEncoding = "gzip";
  if (gzipEncoding.equals(respHeaders.get(HttpHeaders.CONTENT_ENCODING))) {
    inputStream = new GZIPInputStream(inputStream);
  }
  HttpResult result = new HttpResult(respCode, IOUtils.toString(inputStream, getCharset(conn)), respHeaders);
  inputStream.close();
  return result;
}

代码示例来源:origin: libgdx/libgdx

private InputStream getInputStream () {
    try {
      return connection.getInputStream();
    } catch (IOException e) {
      return connection.getErrorStream();
    }
  }
}

代码示例来源:origin: foxinmy/weixin4j

connection.setRequestMethod(method);
connection.setDoInput(true);
connection.setInstanceFollowRedirects("GET".equals(method));
InputStream input = connection.getErrorStream() != null ? connection
    .getErrorStream() : connection.getInputStream();
byte[] content = IOUtil.toByteArray(input);
response = new SimpleHttpResponse(connection, content);

代码示例来源:origin: apache/servicemix

public void deletePerson(int id) throws Exception{
  String url = PERSON_SERVICE_URL+"person/delete/"+id;
  System.out.println("\n### DELETE PERSON WITH ID "+id+" FROM URL "+url);
  HttpURLConnection connection = (HttpURLConnection) connect(url);
  connection.setRequestMethod("DELETE");
  connection.setDoInput(true);
  System.out.println("Status: " + connection.getResponseCode() + " " +
      connection.getResponseMessage());
  if (connection.getResponseCode() / 100 != 2) {
    System.out.println(IOUtils.toString(connection.getErrorStream()));
  }
}

代码示例来源:origin: stackoverflow.com

URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
if (connection instanceof HttpURLConnection) {
  HttpURLConnection httpConn = (HttpURLConnection) connection;
  int statusCode = httpConn.getResponseCode();
  if (statusCode != 200 /* or statusCode >= 200 && statusCode < 300 */) {
   is = httpConn.getErrorStream();
  }
}

代码示例来源:origin: stackoverflow.com

InputStream is = null;
try {
  con = (HttpURLConnection) new URL(url).openConnection();
  con.connect();
  boolean isError = con.getResponseCode() >= 400;
  is = isError ? con.getErrorStream() : con.getInputStream();

相关文章

HttpURLConnection类方法