List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:com.cloudant.http.interceptors.CookieInterceptor.java
@Override public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); try {/*www.j ava 2 s. c o m*/ boolean renewCookie = false; int statusCode = connection.getResponseCode(); switch (statusCode) { case HttpURLConnection.HTTP_FORBIDDEN: //403 //check if it was an expiry case InputStream errorStream = connection.getErrorStream(); String errorString = new String(IOUtils.toString(errorStream, "UTF-8")); try { JsonObject errorResponse = new Gson().fromJson(errorString, JsonObject.class); String error = errorResponse.getAsJsonPrimitive("error").getAsString(); String reason = errorResponse.getAsJsonPrimitive("reason").getAsString(); if (!"credentials_expired".equals(error)) { //wasn't a credentials expired, throw exception throw new HttpConnectionInterceptorException(error, reason); } else { // Was expired - set boolean to renew cookie renewCookie = true; } } catch (JsonParseException e) { //wasn't JSON throw an exception throw new HttpConnectionInterceptorException(errorString); } finally { errorStream.close(); } break; case HttpURLConnection.HTTP_UNAUTHORIZED: //401 // We need to get a new cookie renewCookie = true; break; default: break; } if (renewCookie) { cookie = getCookie(connection.getURL(), context); // Don't resend request, failed to get cookie if (cookie != null) { context.replayRequest = true; } else { context.replayRequest = false; } } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to get response code from request", e); } return context; }
From source file:org.jongo.mocks.JongoClient.java
private JongoResponse doRequest(final String url, final String method) { JongoResponse response = null;/*from ww w . j av a2 s . c o m*/ try { HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection(); con.setRequestMethod(method); con.setDoOutput(true); con.setRequestProperty("Accept", MediaType.APPLICATION_XML); BufferedReader r = null; if (con.getResponseCode() != Response.Status.OK.getStatusCode()) { r = new BufferedReader(new InputStreamReader(con.getErrorStream())); } else { r = new BufferedReader(new InputStreamReader(con.getInputStream())); } StringBuilder rawresponse = new StringBuilder(); String strLine = null; while ((strLine = r.readLine()) != null) { rawresponse.append(strLine); rawresponse.append("\n"); } try { response = XmlXstreamTest.successFromXML(rawresponse.toString()); } catch (Exception e) { response = XmlXstreamTest.errorFromXML(rawresponse.toString()); } } catch (Exception ex) { ex.printStackTrace(); } return response; }
From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java
public static HttpResponse doGet(String endpoint, Map<String, String> headers) throws IOException { HttpResponse httpResponse;//from w ww . j a v a 2 s .c om if (endpoint.startsWith("http://")) { URL url = new URL(endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setReadTimeout(30000); // setting headers if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); conn.setRequestProperty(key, headers.get(key)); } } conn.connect(); // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode()); httpResponse.setResponseMessage(conn.getResponseMessage()); } catch (IOException ignored) { rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode()); httpResponse.setResponseMessage(conn.getResponseMessage()); } finally { if (rd != null) { rd.close(); } } return httpResponse; } return null; }
From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.AbstractApiControllerTest.java
@NotNull protected Tuple2<Integer, String> fetchText(final String rel, final String expectedContentType) throws Exception { final HttpURLConnection conn = (HttpURLConnection) resolve(rel).toURL().openConnection(); try {/* w w w . j a va 2s. c o m*/ conn.setRequestProperty("Accept", expectedContentType); conn.connect(); final int responseCode = conn.getResponseCode(); InputStream in; try { in = conn.getInputStream(); } catch (final IOException e) { in = conn.getErrorStream(); } if (in == null) { return Tuple2.tuple2(responseCode, ""); } assertEquals(expectedContentType, conn.getHeaderField("Content-Type")); try { final StringBuilder sb = new StringBuilder(); int rd; while ((rd = in.read()) != -1) { sb.append((char) rd); } return Tuple2.tuple2(responseCode, sb.toString()); } finally { in.close(); } } finally { conn.disconnect(); } }
From source file:dk.clarin.tools.workflow.java
/** * Sends an HTTP GET request to a url/*from www . ja v a 2 s .c o m*/ * * @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search") * @param requestString - all the request parameters (Example: "param1=val1¶m2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself * @return - The response from the end point */ public static int sendRequest(String result, String endpoint, String requestString, bracmat BracMat, String filename, String jobID, boolean postmethod) { int code = 0; String message = ""; //String filelist; if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) { // Send a GET or POST request to the servlet try { // Construct data String requestResult = ""; String urlStr = endpoint; if (postmethod) // HTTP POST { logger.debug("HTTP POST"); StringReader input = new StringReader(requestString); StringWriter output = new StringWriter(); URL endp = new URL(endpoint); HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) endp.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(input, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) out.close(); } } catch (IOException e) { throw new Exception("Connection error (is server running at " + endp + " ?): " + e); } finally { if (urlc != null) { code = urlc.getResponseCode(); if (code == 200) { got200(result, BracMat, filename, jobID, urlc.getInputStream()); } else { InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); requestResult = output.toString(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) in.close(); } logger.debug("urlc.getResponseCode() == {}", code); message = urlc.getResponseMessage(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } urlc.disconnect(); } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } //requestResult = output.toString(); logger.debug("postData returns " + requestResult); } else // HTTP GET { logger.debug("HTTP GET"); // Send data if (requestString != null && requestString.length() > 0) { urlStr += "?" + requestString; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); conn.connect(); // Cast to a HttpURLConnection if (conn instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) conn; code = httpConnection.getResponseCode(); logger.debug("httpConnection.getResponseCode() == {}", code); message = httpConnection.getResponseMessage(); BufferedReader rd; StringBuilder sb = new StringBuilder(); ; //String line; if (code == 200) { got200(result, BracMat, filename, jobID, httpConnection.getInputStream()); } else { // Get the error response rd = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream())); int nextChar; while ((nextChar = rd.read()) != -1) { sb.append((char) nextChar); } rd.close(); requestResult = sb.toString(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } logger.debug("Job " + jobID + " receives status code [" + code + "] from tool."); } catch (Exception e) { //jobs = 0; // No more jobs to process now, probably the tool is not reachable logger.warn("Job " + jobID + " aborted. Reason:" + e.getMessage()); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } } else { //jobs = 0; // No more jobs to process now, probably the tool is not integrated at all logger.warn("Job " + jobID + " aborted. Endpoint must start with 'http://' or 'https://'. (" + endpoint + ")"); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } return code; }
From source file:org.jboss.aerogear.android.impl.http.HttpRestProviderTest.java
private void testDelete(int statusCode) throws Exception { HttpURLConnection connection = mock(HttpURLConnection.class); HttpUrlConnectionProvider providerProvider = new HttpUrlConnectionProvider(connection); final String id = "1"; when(connection.getResponseCode()).thenReturn(statusCode); when(connection.getInputStream()).thenReturn(new ByteArrayInputStream(EMPTY_DATA)); when(connection.getErrorStream()).thenReturn(new ByteArrayInputStream(EMPTY_DATA)); when(connection.getHeaderFields()).thenReturn(RESPONSE_HEADERS); doCallRealMethod().when(connection).setRequestMethod(anyString()); when(connection.getRequestMethod()).thenCallRealMethod(); HttpRestProvider provider = new HttpRestProvider(SIMPLE_URL); setPrivateField(provider, "connectionPreparer", providerProvider); HeaderAndBody result = provider.delete(id); assertArrayEquals(EMPTY_DATA, result.getBody()); assertEquals("DELETE", connection.getRequestMethod()); assertNotNull(result.getHeader(HEADER_KEY1_NAME)); assertNotNull(result.getHeader(HEADER_KEY2_NAME)); assertEquals(HEADER_VALUE, result.getHeader(HEADER_KEY2_NAME)); assertEquals(id, providerProvider.id); }
From source file:com.omertron.themoviedbapi.tools.WebBrowser.java
public static String request(URL url, String jsonBody, boolean isDeleteRequest) throws MovieDbException { StringWriter content = null;/* w ww.ja v a 2s . c o m*/ try { content = new StringWriter(); BufferedReader in = null; HttpURLConnection cnx = null; OutputStreamWriter wr = null; try { cnx = (HttpURLConnection) openProxiedConnection(url); // If we get a null connection, then throw an exception if (cnx == null) { throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, "No HTTP connection could be made.", url); } if (isDeleteRequest) { cnx.setDoOutput(true); cnx.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); cnx.setRequestMethod("DELETE"); } sendHeader(cnx); if (StringUtils.isNotBlank(jsonBody)) { cnx.setDoOutput(true); wr = new OutputStreamWriter(cnx.getOutputStream()); wr.write(jsonBody); } readHeader(cnx); // http://stackoverflow.com/questions/4633048/httpurlconnection-reading-response-content-on-403-error if (cnx.getResponseCode() >= 400) { in = new BufferedReader(new InputStreamReader(cnx.getErrorStream(), getCharset(cnx))); } else { in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx))); } String line; while ((line = in.readLine()) != null) { content.write(line); } } finally { if (wr != null) { wr.flush(); wr.close(); } if (in != null) { in.close(); } if (cnx instanceof HttpURLConnection) { ((HttpURLConnection) cnx).disconnect(); } } return content.toString(); } catch (IOException ex) { throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, null, url, ex); } finally { if (content != null) { try { content.close(); } catch (IOException ex) { LOG.debug("Failed to close connection: " + ex.getMessage()); } } } }
From source file:org.apache.olingo.fit.tecsvc.http.ODataVersionConformanceITCase.java
@Test public void invalidODataVersionHeader1() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ODATA_VERSION, "3.0"); connection.connect();//from w ww . ja va 2s . c o m assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode()); assertEquals("4.0", connection.getHeaderField(HttpHeader.ODATA_VERSION)); final String content = IOUtils.toString(connection.getErrorStream()); assertTrue(content.contains("OData version '3.0' is not supported.")); }
From source file:org.apache.olingo.fit.tecsvc.http.ODataVersionConformanceITCase.java
@Test public void invalidODataVersionHeader2() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ODATA_VERSION, "5.0"); connection.connect();//from w ww .j a v a2s .c om assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode()); assertEquals("4.0", connection.getHeaderField(HttpHeader.ODATA_VERSION)); final String content = IOUtils.toString(connection.getErrorStream()); assertTrue(content.contains("OData version '5.0' is not supported.")); }
From source file:org.apache.olingo.fit.tecsvc.http.ODataVersionConformanceITCase.java
@Test public void invalidODataMaxVersionHeader1() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ODATA_MAX_VERSION, "3.0"); connection.connect();/*from w ww . j a v a 2s. com*/ assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode()); assertEquals("4.0", connection.getHeaderField(HttpHeader.ODATA_VERSION)); final String content = IOUtils.toString(connection.getErrorStream()); assertTrue(content.contains("OData version '3.0' is not supported.")); }