javax.net.ssl.HttpsURLConnection.getErrorStream()方法的使用及代码示例

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

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

HttpsURLConnection.getErrorStream介绍

暂无

代码示例

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

public Response(HttpsURLConnection https) throws IOException {
  this.https = https;
  this.status = https.getResponseCode();
  if (null == (is = https.getErrorStream())) {
    is = https.getInputStream();
  }
}

代码示例来源:origin: com.microsoft.azure.iothub-java-client/iothub-java-device-client

/**
 * Reads from the error stream and returns the error reason.
 *
 * @return the error reason.
 *
 * @throws IOException if the input stream could not be accessed, for
 * example if the server could not be reached.
 */
public byte[] readError() throws IOException
{
  // Codes_SRS_HTTPSCONNECTION_11_013: [The function shall read from the error stream and return the response.]
  // Codes_SRS_HTTPSCONNECTION_11_014: [The function shall throw an IOException if the error stream could not be accessed.]
  InputStream errorStream = this.connection.getErrorStream();
  byte[] error = new byte[0];
  // if there is no error reason, getErrorStream() returns null.
  if (errorStream != null)
  {
    error = readInputStream(errorStream);
    // Codes_SRS_HTTPSCONNECTION_11_020: [The function shall close the error stream after it has been completely read.]
    errorStream.close();
  }
  return error;
}

代码示例来源:origin: Azure/azure-iot-sdk-java

/**
 * Reads from the error stream and returns the error reason.
 *
 * @return The error reason.
 *
 * @throws IOException This exception thrown if the input stream could not be
 * accessed, for example if the server could not be reached.
 */
public byte[] readError() throws IOException
{
  byte[] error = new byte[0];
  try (InputStream errorStream = this.connection.getErrorStream())
  {
    // Codes_SRS_SERVICE_SDK_JAVA_HTTPCONNECTION_12_017: [The function shall read from the error stream and return the response.]
    // Codes_SRS_SERVICE_SDK_JAVA_HTTPCONNECTION_12_018: [The function shall throw an IOException if the error stream could not be accessed.]
    // if there is no error reason, getErrorStream() returns null.
    if (errorStream != null)
    {
      error = readInputStream(errorStream);
    }
    // Codes_SRS_SERVICE_SDK_JAVA_HTTPCONNECTION_12_019: [The function shall close the error stream after it has been completely read.]
  }
  return error;
}

代码示例来源:origin: Azure/azure-iot-sdk-java

/**
 * Reads from the error stream and returns the error reason.
 *
 * @return The error reason.
 *
 * @throws IOException This exception thrown if the input stream could not be
 * accessed, for example if the server could not be reached.
 */
public byte[] readError() throws IOException
{
  byte[] error = new byte[0];
  try (InputStream errorStream = this.connection.getErrorStream())
  {
    // Codes_SRS_HTTPCONNECTION_25_017: [The function shall read from the error stream and return the response.]
    // Codes_SRS_HTTPCONNECTION_25_018: [The function shall throw an IOException if the error stream could not be accessed.]
    // Codes_SRS_HTTPCONNECTION_25_019: [The function shall close the error stream after it has been completely read.]
    // if there is no error reason, getErrorStream() returns null.
    if (errorStream != null)
    {
      error = readInputStream(errorStream);
    }
  }
  return error;
}

代码示例来源:origin: com.facebook.ads.sdk/facebook-java-ads-sdk

private static String readResponse(HttpsURLConnection con) throws APIException, IOException {
 try {
  int responseCode = con.getResponseCode();
  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuilder response = new StringBuilder();
  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();
  return response.toString();
 } catch(Exception e) {
  BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
  String inputLine;
  StringBuilder response = new StringBuilder();
  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();
  throw new APIException.FailedRequestException(response.toString(), e);
 }
}

代码示例来源:origin: org.wso2.esb.integration/integration-base

/**
 * Read response from {@link HttpsURLConnection}
 *
 * @param con HttpsURLConnection.
 * @return String content of the HTTP response.
 * @throws IOException
 */
private String readResponseHTTPS(HttpsURLConnection con) throws IOException {
  InputStream responseStream = null;
  String responseString = null;
  if (con.getResponseCode() >= 400) {
    responseStream = con.getErrorStream();
  } else {
    responseStream = con.getInputStream();
  }
  if (responseStream != null) {
    StringBuilder stringBuilder = new StringBuilder();
    byte[] bytes = new byte[1024];
    int len;
    while ((len = responseStream.read(bytes)) != -1) {
      stringBuilder.append(new String(bytes, 0, len));
    }
    if (!stringBuilder.toString().trim().isEmpty()) {
      responseString = stringBuilder.toString();
    }
  }
  return responseString;
}

代码示例来源:origin: facebook/facebook-java-business-sdk

private static ResponseWrapper readResponse(HttpsURLConnection con) throws APIException, IOException {
 try {
  int responseCode = con.getResponseCode();
  String header = convertToString(con.getHeaderFields());
  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuilder response = new StringBuilder();
  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();
  return new ResponseWrapper(response.toString(), header);
 } catch(Exception e) {
  BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
  String inputLine;
  StringBuilder response = new StringBuilder();
  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();
  throw new APIException.FailedRequestException(response.toString(), e);
 }
}

代码示例来源:origin: ihaolin/antares

private String doRequest() {
  if (!Strings.isNullOrEmpty(body)){
    try (OutputStream out = connection.getOutputStream()){
      out.write(body.getBytes());
    } catch (IOException e) {
      throw new HttpException(e);
    }
  }
  int respCode;
  try {
    respCode = connection.getResponseCode();
  } catch (IOException e) {
    throw new HttpException(e);
  }
  try (InputStream in = respCode == HttpURLConnection.HTTP_OK ?
         connection.getInputStream() : connection.getErrorStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
    StringBuilder content = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
      content.append(line);
    }
    return content.toString();
  } catch (IOException e) {
    throw new HttpException(e);
  }
}

代码示例来源:origin: org.wso2.esb.integration/integration-base

/**
 * Send HTTP request using {@link HttpURLConnection} in JSON format to return {@link InputStream}.
 *
 * @param endPoint String End point URL.
 * @param httpMethod String HTTP method type (GET, POST, PUT etc.)
 * @param headersMap Map<String, String> Headers need to send to the end point.
 * @param requestFileName String File name of the file which contains request body data.
 * @param parametersMap Map<String, String> Additional parameters which is not predefined in the
 *        properties file.
 * @return InputStream
 * @throws IOException
 * @throws XMLStreamException
 */
protected InputStream processForInputStreamHTTPS(String endPoint, String httpMethod,
    Map<String, String> headersMap, String requestFileName, Map<String, String> parametersMap,
    boolean isIgnoreHostVerification) throws IOException, JSONException {
  HttpsURLConnection httpsConnection =
      writeRequestHTTPS(endPoint, httpMethod, RestResponse.JSON_TYPE, headersMap, requestFileName,
          parametersMap, isIgnoreHostVerification);
  InputStream responseStream = null;
  if (httpsConnection.getResponseCode() >= 400) {
    responseStream = httpsConnection.getErrorStream();
  } else {
    responseStream = httpsConnection.getInputStream();
  }
  return responseStream;
}

代码示例来源:origin: wso2-attic/esb-connectors

responseStream = httpsConnection.getErrorStream();
} else {
  responseStream = httpsConnection.getInputStream();

代码示例来源:origin: com.solidfire/jsvcgen-client-java

/**
 * Dispatch an encoded request to the system and await some response.
 *
 * Can throw java.net.SocketTimeoutException if the connection or read timeout occurs.
 *
 * @param input The input string to send to the remote server.
 * @return The server's response.
 * @throws IOException if anything went wrong on the connection side of things.
 */
@Override
public String dispatchRequest(String input) throws IOException {
  final byte[] encodedRequest = input.getBytes();
  final HttpsURLConnection connection = (HttpsURLConnection) endpoint.openConnection();
  prepareConnection(connection);
  try (OutputStream out = connection.getOutputStream()) {
    out.write(encodedRequest);
    out.flush();
  }
  // JSON-RPC...we don't actually care about the response code
  final InputStream response = connection.getResponseCode() == 200 ? connection.getInputStream() : connection.getErrorStream();
  try {
    return decodeResponse(response);
  } finally {
    if (null != response) {
      response.close();
    }
  }
}

代码示例来源:origin: line/line-sdk-android

private void setErrorData(int httpErrorCode, @NonNull byte[] byteArray) throws IOException {
  InputStream inputStream = new ByteArrayInputStream(byteArray);
  doReturn(inputStream).when(httpsURLConnection).getErrorStream();
  doReturn(httpErrorCode).when(httpsURLConnection).getResponseCode();
}

代码示例来源:origin: me.hao0/common

private String doRequest() {
  if (!Strings.isNullOrEmpty(body)){
    try (OutputStream out = connection.getOutputStream()){
      out.write(body.getBytes());
    } catch (IOException e) {
      throw new HttpsException(e);
    }
  }
  int respCode;
  try {
    respCode = connection.getResponseCode();
  } catch (IOException e) {
    throw new HttpsException(e);
  }
  try (InputStream in = respCode == HttpURLConnection.HTTP_OK ?
         connection.getInputStream() : connection.getErrorStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
    StringBuilder content = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
      content.append(line);
    }
    return content.toString();
  } catch (IOException e) {
    throw new HttpsException(e);
  }
}

代码示例来源:origin: org.shipkit/shipkit

private String call(String method, HttpsURLConnection conn) throws IOException {
    LOG.info("  Calling {} {}. Turn on debug logging to see response headers.", method, conn.getURL());

    if (conn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
      return IOUtil.readFully(conn.getInputStream());
    } else {
      String errorMessage =
        String.format("%s %s failed, response code = %s, response body:\n%s",
          method, conn.getURL(), conn.getResponseCode(), IOUtil.readFully(conn.getErrorStream()));
      throw new IOException(errorMessage);
    }
  }
}

代码示例来源:origin: mockito/shipkit

private String call(String method, HttpsURLConnection conn) throws IOException {
    LOG.info("  Calling {} {}. Turn on debug logging to see response headers.", method, conn.getURL());

    if (conn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
      return IOUtil.readFully(conn.getInputStream());
    } else {
      String errorMessage =
        String.format("%s %s failed, response code = %s, response body:\n%s",
          method, conn.getURL(), conn.getResponseCode(), IOUtil.readFully(conn.getErrorStream()));
      throw new IOException(errorMessage);
    }
  }
}

代码示例来源:origin: com.microsoft.azure/adal4j

static String readResponseFromConnection(final HttpsURLConnection conn)
    throws AuthenticationException, IOException {
  InputStream is = null;
  try {
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
      String msg = "Server returned HTTP response code: " + conn.getResponseCode() + " for URL : " +
          conn.getURL();
      is = conn.getErrorStream();
      if (is != null) {
        msg = msg + ", Error details : " + inputStreamToString(is);
      }
      throw new AuthenticationException(msg);
    }
    is = conn.getInputStream();
    return inputStreamToString(is);
  }
  finally {
    if(is != null){
      is.close();
    }
  }
}

代码示例来源:origin: Microsoft/azure-tools-for-java

@NotNull
private static HttpResponse getResponse(@NotNull HttpsURLConnection sslConnection)
    throws IOException {
  int code = sslConnection.getResponseCode();
  String message = Strings.nullToEmpty(sslConnection.getResponseMessage());
  Map<String, List<String>> headers = sslConnection.getHeaderFields();
  if (headers == null) {
    headers = new HashMap<String, List<String>>();
  }
  InputStream is;
  String content;
  try {
    is = sslConnection.getInputStream();
  } catch (IOException e) {
    is = sslConnection.getErrorStream();
  }
  if (is != null) {
    content = readStream(is);
  } else {
    content = "";
  }
  return new HttpResponse(code, message, headers, content);
}

代码示例来源:origin: AzureAD/azure-activedirectory-library-for-java

static String readResponseFromConnection(final HttpsURLConnection conn)
    throws AuthenticationException, IOException {
  InputStream is = null;
  try {
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
      String msg = "Server returned HTTP response code: " + conn.getResponseCode() + " for URL : " +
          conn.getURL();
      is = conn.getErrorStream();
      if (is != null) {
        msg = msg + ", Error details : " + inputStreamToString(is);
      }
      throw new AuthenticationException(msg);
    }
    is = conn.getInputStream();
    return inputStreamToString(is);
  }
  finally {
    if(is != null){
      is.close();
    }
  }
}

代码示例来源:origin: Microsoft/AppCenter-SDK-Android

@Test
public void get100() throws Exception {
  /* Configure mock HTTP. */
  URL url = mock(URL.class);
  whenNew(URL.class).withAnyArguments().thenReturn(url);
  HttpsURLConnection urlConnection = mock(HttpsURLConnection.class);
  when(url.openConnection()).thenReturn(urlConnection);
  when(urlConnection.getResponseCode()).thenReturn(100);
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  when(urlConnection.getOutputStream()).thenReturn(buffer);
  when(urlConnection.getErrorStream()).thenReturn(new ByteArrayInputStream("Continue".getBytes()));
  /* Configure API client. */
  DefaultHttpClient httpClient = new DefaultHttpClient();
  /* Test calling code. */
  Map<String, String> headers = new HashMap<>();
  ServiceCallback serviceCallback = mock(ServiceCallback.class);
  mockCall();
  httpClient.callAsync("", METHOD_POST, headers, null, serviceCallback);
  verify(serviceCallback).onCallFailed(new HttpException(100, "Continue"));
  verifyNoMoreInteractions(serviceCallback);
  verify(urlConnection).disconnect();
}

代码示例来源:origin: Microsoft/AppCenter-SDK-Android

@Test
public void cancelledOnReceivingError() throws Exception {
  /* Configure mock HTTP. */
  String urlString = "http://mock/get";
  URL url = mock(URL.class);
  whenNew(URL.class).withArguments(urlString).thenReturn(url);
  HttpsURLConnection urlConnection = mock(HttpsURLConnection.class);
  when(url.openConnection()).thenReturn(urlConnection);
  when(urlConnection.getResponseCode()).thenReturn(503);
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  when(urlConnection.getOutputStream()).thenReturn(buffer);
  when(urlConnection.getErrorStream()).thenReturn(new ByteArrayInputStream("Busy".getBytes()));
  mockCall(new Consumer<DefaultHttpClientCallTask>() {
    @Override
    public void accept(final DefaultHttpClientCallTask call) {
      when(call.isCancelled()).thenReturn(false, false, true);
    }
  });
  /* Call and verify */
  HttpClient.CallTemplate callTemplate = mock(HttpClient.CallTemplate.class);
  ServiceCallback serviceCallback = mock(ServiceCallback.class);
  DefaultHttpClient httpClient = new DefaultHttpClient();
  ServiceCall call = httpClient.callAsync(urlString, METHOD_GET, new HashMap<String, String>(), callTemplate, serviceCallback);
  verify(serviceCallback).onCallFailed(new HttpException(503, "Busy"));
  assertEquals(0, httpClient.getTasks().size());
}

相关文章

HttpsURLConnection类方法