List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:com.googlecode.jmxtrans.model.output.support.HttpOutputWriter.java
private void consumeInputStreams(HttpURLConnection httpURLConnection) throws IOException { Closer closer = Closer.create();//from ww w . ja va 2 s. c o m try { InputStream in = closer.register(httpURLConnection.getInputStream()); InputStream err = closer.register(httpURLConnection.getErrorStream()); copy(in, nullOutputStream()); if (err != null) copy(err, nullOutputStream()); } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } }
From source file:com.denimgroup.threadfix.service.defects.RestUtils.java
public static InputStream postUrl(String urlString, String data, String username, String password) { URL url = null;/*from w w w . j av a 2s. co m*/ try { url = new URL(urlString); } catch (MalformedURLException e) { log.warn("URL used for POST was bad: '" + urlString + "'"); return null; } HttpURLConnection httpConnection = null; OutputStreamWriter outputWriter = null; try { httpConnection = (HttpURLConnection) url.openConnection(); setupAuthorization(httpConnection, username, password); httpConnection.addRequestProperty("Content-Type", "application/json"); httpConnection.addRequestProperty("Accept", "application/json"); httpConnection.setDoOutput(true); outputWriter = new OutputStreamWriter(httpConnection.getOutputStream()); outputWriter.write(data); outputWriter.flush(); InputStream is = httpConnection.getInputStream(); return is; } catch (IOException e) { log.warn("IOException encountered trying to post to URL with message: " + e.getMessage()); if (httpConnection == null) { log.warn( "HTTP connection was null so we cannot do further debugging of why the HTTP request failed"); } else { try { InputStream errorStream = httpConnection.getErrorStream(); if (errorStream == null) { log.warn("Error stream from HTTP connection was null"); } else { log.warn( "Error stream from HTTP connection was not null. Attempting to get response text."); String postErrorResponse = IOUtils.toString(errorStream); log.warn("Error text in response was '" + postErrorResponse + "'"); } } catch (IOException e2) { log.warn("IOException encountered trying to read the reason for the previous IOException: " + e2.getMessage(), e2); } } } finally { if (outputWriter != null) { try { outputWriter.close(); } catch (IOException e) { log.warn("Failed to close output stream in postUrl.", e); } } } return null; }
From source file:org.apache.ambari.server.controller.metrics.timeline.MetricsRequestHelper.java
private boolean checkConnectionForPrecisionException(HttpURLConnection connection) throws IOException, URISyntaxException { if (connection != null && connection.getResponseCode() == HttpStatus.SC_BAD_REQUEST) { InputStream errorStream = connection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream)); String errorMessage = reader.readLine(); if (errorMessage != null && errorMessage.contains("PrecisionLimitExceededException")) { LOG.debug("Encountered Precision exception while requesting metrics : " + errorMessage); return false; } else {/*www.j a v a 2 s. c o m*/ throw new IOException(errorMessage); } } return true; }
From source file:com.expertiseandroid.lib.sociallib.utils.Utils.java
/** * Sends a POST request with an attached object * @param url the url that should be opened * @param params the body parameters/* w w w . java2 s.c o m*/ * @param attachment the object to be attached * @return the response * @throws IOException */ public static String postWithAttachment(String url, Map<String, String> params, Object attachment) throws IOException { String boundary = generateBoundaryString(10); URL servUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) servUrl.openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + SOCIALLIB); conn.setRequestMethod("POST"); String contentType = "multipart/form-data; boundary=" + boundary; conn.setRequestProperty("Content-Type", contentType); byte[] body = generatePostBody(params, attachment, boundary); conn.setDoOutput(true); conn.connect(); OutputStream out = conn.getOutputStream(); out.write(body); InputStream is = null; try { is = conn.getInputStream(); } catch (FileNotFoundException e) { is = conn.getErrorStream(); } catch (Exception e) { int statusCode = conn.getResponseCode(); Log.e("Response code", "" + statusCode); return conn.getResponseMessage(); } BufferedReader r = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String l; while ((l = r.readLine()) != null) sb.append(l).append('\n'); out.close(); is.close(); if (conn != null) conn.disconnect(); return sb.toString(); }
From source file:com.gmt2001.HttpRequest.java
public static HttpResponse getData(RequestType type, String url, String post, HashMap<String, String> headers) { Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance()); HttpResponse r = new HttpResponse(); r.type = type;//from ww w . j av a2s . c o m r.url = url; r.post = post; r.headers = headers; try { URL u = new URL(url); HttpURLConnection h = (HttpURLConnection) u.openConnection(); for (Entry<String, String> e : headers.entrySet()) { h.addRequestProperty(e.getKey(), e.getValue()); } h.setRequestMethod(type.name()); h.setUseCaches(false); h.setDefaultUseCaches(false); h.setConnectTimeout(timeout); h.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); if (!post.isEmpty()) { h.setDoOutput(true); } h.connect(); if (!post.isEmpty()) { BufferedOutputStream stream = new BufferedOutputStream(h.getOutputStream()); stream.write(post.getBytes()); stream.flush(); stream.close(); } if (h.getResponseCode() < 400) { r.content = IOUtils.toString(new BufferedInputStream(h.getInputStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = true; } else { r.content = IOUtils.toString(new BufferedInputStream(h.getErrorStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = false; } } catch (IOException ex) { r.success = false; r.httpCode = 0; r.exception = ex.getMessage(); com.gmt2001.Console.err.printStackTrace(ex); } return r; }
From source file:com.markuspage.jbinrepoproxy.standalone.transport.sun.URLConnectionTransportClientImpl.java
@Override public TransportFetch httpGetOtherFile(String uri) { TransportFetch result;// w ww . ja va2 s . c o m try { final URL url = new URL(serverURL + uri); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(false); final int responseCode = conn.getResponseCode(); final String responseMessage = conn.getResponseMessage(); InputStream responseIn = conn.getErrorStream(); if (responseIn == null) { responseIn = conn.getInputStream(); } // Read the body to the output if OK otherwise to the error message final byte[] body = IOUtils.toByteArray(responseIn); result = new TransportFetch(responseCode, responseMessage, body); } catch (MalformedURLException ex) { LOG.error("Malformed URL", ex); result = new TransportFetch(500, ex.getLocalizedMessage(), null); } catch (IOException ex) { LOG.error("IO error", ex); result = new TransportFetch(500, ex.getLocalizedMessage(), null); } return result; }
From source file:com.markuspage.jbinrepoproxy.standalone.transport.sun.URLConnectionTransportClientImpl.java
@Override public TransportFetch httpGetTheFile() { TransportFetch result;// w ww. j a v a 2 s . c om try { final URL url = new URL(serverURL + theFileURI); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(false); final int responseCode = conn.getResponseCode(); final String responseMessage = conn.getResponseMessage(); InputStream responseIn = conn.getErrorStream(); if (responseIn == null) { responseIn = conn.getInputStream(); } // Read the body to the output if OK otherwise to the error message final byte[] body = IOUtils.toByteArray(responseIn); this.targetResponse = new TargetResponse(responseCode, conn.getHeaderFields(), body); result = new TransportFetch(responseCode, responseMessage, body); } catch (MalformedURLException ex) { LOG.error("Malformed URL", ex); result = new TransportFetch(500, ex.getLocalizedMessage(), null); } catch (IOException ex) { LOG.error("IO error", ex); result = new TransportFetch(500, ex.getLocalizedMessage(), null); } return result; }
From source file:org.jboss.aerogear.android.impl.http.HttpRestProviderTest.java
@Test(expected = HttpException.class) public void testGetFailsWith404() throws Exception { HttpURLConnection connection404 = mock(HttpURLConnection.class); doReturn(HttpStatus.SC_NOT_FOUND).when(connection404).getResponseCode(); when(connection404.getErrorStream()).thenReturn(new ByteArrayInputStream(RESPONSE_DATA)); HttpRestProvider provider = new HttpRestProvider(SIMPLE_URL); setPrivateField(provider, "connectionPreparer", new HttpUrlConnectionProvider(connection404)); try {//from w w w .j a v a 2 s. c o m provider.get(); } catch (HttpException exception) { assertArrayEquals(RESPONSE_DATA, exception.getData()); assertEquals(HttpStatus.SC_NOT_FOUND, exception.getStatusCode()); throw exception; } }
From source file:org.apache.hadoop.hive.ql.exec.tez.YarnQueueHelper.java
public String handleUnexpectedStatusCode(HttpURLConnection connection, int statusCode, String errorStr) throws IOException { // We do no handle anything but OK for now. Again, we need a real client for this API. // TODO: handle 401 and return a new connection? nothing for now InputStream errorStream = connection.getErrorStream(); String error = "Received " + statusCode + (errorStr == null ? "" : (" (" + errorStr + ")")); if (errorStream != null) { error += ": " + IOUtils.toString(errorStream); } else {/*from w w w.ja va 2s . c o m*/ errorStream = connection.getInputStream(); if (errorStream != null) { error += ": " + IOUtils.toString(errorStream); } } return error; }
From source file:com.cloudbees.mtslaves.client.RemoteReference.java
protected void verifyResponseStatus(HttpURLConnection con) throws IOException { if (con.getResponseCode() / 100 != 2) { String msg = "Failed to call " + con.getURL() + " : " + con.getResponseCode() + ' ' + con.getResponseMessage(); InputStream es = con.getErrorStream(); String ct = con.getContentType(); if (ct != null) { HttpHeader contentType = HttpHeader.parse(ct); if (contentType.value.equals("application/json")) { // if the error is JSON, parse it if (es != null) { JSONObject error = JSONObject .fromObject(IOUtils.toString(es, contentType.getSubHeader("charset", "UTF-8"))); throw new ServerException(msg, error, con.getResponseCode(), con.getResponseMessage(), con.getURL()); }// w ww . java 2s . c o m } } if (es != null) msg += "\n" + IOUtils.toString(es); throw new IOException(msg); } }