List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:io.confluent.kafka.schemaregistry.client.rest.RestService.java
/** * @param requestUrl HTTP connection will be established with this url. * @param method HTTP method ("GET", "POST", "PUT", etc.) * @param requestBodyData Bytes to be sent in the request body. * @param requestProperties HTTP header properties. * @param responseFormat Expected format of the response to the HTTP request. * @param <T> The type of the deserialized response to the HTTP request. * @return The deserialized response to the HTTP request, or null if no data is expected. *///from w ww . j av a 2 s.c o m private <T> T sendHttpRequest(String requestUrl, String method, byte[] requestBodyData, Map<String, String> requestProperties, TypeReference<T> responseFormat) throws IOException, RestClientException { log.debug(String.format("Sending %s with input %s to %s", method, requestBodyData == null ? "null" : new String(requestBodyData), requestUrl)); HttpURLConnection connection = null; try { URL url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); // connection.getResponseCode() implicitly calls getInputStream, so always set to true. // On the other hand, leaving this out breaks nothing. connection.setDoInput(true); for (Map.Entry<String, String> entry : requestProperties.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } connection.setUseCaches(false); if (requestBodyData != null) { connection.setDoOutput(true); OutputStream os = null; try { os = connection.getOutputStream(); os.write(requestBodyData); os.flush(); } catch (IOException e) { log.error("Failed to send HTTP request to endpoint: " + url, e); throw e; } finally { if (os != null) os.close(); } } int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); T result = jsonDeserializer.readValue(is, responseFormat); is.close(); return result; } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { return null; } else { InputStream es = connection.getErrorStream(); ErrorMessage errorMessage; try { errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class); } catch (JsonProcessingException e) { errorMessage = new ErrorMessage(JSON_PARSE_ERROR_CODE, e.getMessage()); } es.close(); throw new RestClientException(errorMessage.getMessage(), responseCode, errorMessage.getErrorCode()); } } finally { if (connection != null) { connection.disconnect(); } } }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java
/** * Reads the response from the URL connection. * * @param conn/* w w w . j ava 2s . c om*/ * URL from which to read response * @param res * {@link SampleResult} to read response into * @return response content * @exception IOException * if an I/O exception occurs */ protected byte[] readResponse(HttpURLConnection conn, SampleResult res) throws IOException { BufferedInputStream in; final int contentLength = conn.getContentLength(); if ((contentLength == 0) && OBEY_CONTENT_LENGTH) { log.info("Content-Length: 0, not reading http-body"); res.setResponseHeaders(getResponseHeaders(conn)); res.latencyEnd(); return NULL_BA; } // works OK even if ContentEncoding is null boolean gzipped = HTTPConstants.ENCODING_GZIP.equals(conn.getContentEncoding()); InputStream instream = null; try { instream = new CountingInputStream(conn.getInputStream()); if (gzipped) { in = new BufferedInputStream(new GZIPInputStream(instream)); } else { in = new BufferedInputStream(instream); } } catch (IOException e) { if (!(e.getCause() instanceof FileNotFoundException)) { log.error("readResponse: " + e.toString()); Throwable cause = e.getCause(); if (cause != null) { log.error("Cause: " + cause); if (cause instanceof Error) { throw (Error) cause; } } } // Normal InputStream is not available InputStream errorStream = conn.getErrorStream(); if (errorStream == null) { log.info("Error Response Code: " + conn.getResponseCode() + ", Server sent no Errorpage"); res.setResponseHeaders(getResponseHeaders(conn)); res.latencyEnd(); return NULL_BA; } log.info("Error Response Code: " + conn.getResponseCode()); if (gzipped) { in = new BufferedInputStream(new GZIPInputStream(errorStream)); } else { in = new BufferedInputStream(errorStream); } } catch (Exception e) { log.error("readResponse: " + e.toString()); Throwable cause = e.getCause(); if (cause != null) { log.error("Cause: " + cause); if (cause instanceof Error) { throw (Error) cause; } } in = new BufferedInputStream(conn.getErrorStream()); } // N.B. this closes 'in' byte[] responseData = readResponse(res, in, contentLength); if (instream != null) { res.setBodySize(((CountingInputStream) instream).getCount()); instream.close(); } return responseData; }
From source file:com.PAB.ibeaconreference.AppEngineSpatial.java
public static Response getOrPost(Request request) { mErrorMessage = null;/* www. j ava 2s. c o m*/ HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof PUT) { byte[] payload = ((PUT) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("PUT"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { int a = conn.getResponseCode(); if (a == 401) { response = new Response(a, conn.getHeaderFields(), new byte[] {}); } InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); a12 = new String(body, "US-ASCII"); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:ir.rasen.charsoo.controller.image_loader.core.download.BaseImageDownloader.java
/** * Retrieves {@link InputStream} of image by URI (image is located in the network). * * @param imageUri Image URI// w w w . j av a2 s . c o m * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for * URL. */ protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException, JSONException { HttpURLConnection conn = createConnection(imageUri, extra); String strImage = ""; int redirectCount = 0; while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) { conn = createConnection(conn.getHeaderField("Location"), extra); redirectCount++; } InputStream imageStream = new InputStream() { @Override public int read() throws IOException { return 0; } }; try { imageStream = conn.getInputStream(); StringBuilder sb = new StringBuilder(); String line; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(imageStream)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } JSONObject jsonObject = new JSONObject(sb.toString()); if (jsonObject != null) { strImage = new JSONObject(jsonObject.getString(Params.RESULT)).getString(Params.IMAGE); imageStream = new ByteArrayInputStream(strImage.getBytes()); } else { imageStream = conn.getInputStream(); } } catch (Exception e) { // Read all data to allow reuse connection (http://bit.ly/1ad35PY) IoUtils.readAndCloseStream(conn.getErrorStream()); try { throw e; } catch (IOException e1) { e1.printStackTrace(); } catch (JSONException e1) { e1.printStackTrace(); } } if (!shouldBeProcessed(conn)) { IoUtils.closeSilently(imageStream); throw new IOException("Image request failed with response code " + conn.getResponseCode()); } return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), strImage.length()); }
From source file:com.athenahealth.api.APIConnection.java
/** * Make the API call.//from w ww. j ava 2 s . c o m * * This method abstracts away the connection, streams, and readers necessary to make an HTTP * request. It also adds in the Authorization header and token. * * @param verb HTTP method to use * @param path URI to find * @param parameters key-value pairs of request parameters * @param headers key-value pairs of request headers * @param secondcall true if this is the retried request * @return the JSON-decoded response * * @throws AthenahealthException If there is an error making the call. * API-level errors are reported in the return-value. */ private Object call(String verb, String path, Map<String, String> parameters, Map<String, String> headers, boolean secondcall) throws AthenahealthException { try { // Join up a url and open a connection URL url = new URL(path_join(getBaseURL(), version, practiceid, path)); HttpURLConnection conn = openConnection(url); conn.setRequestMethod(verb); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // Set the Authorization header using the token, then do the rest of the headers conn.setRequestProperty("Authorization", "Bearer " + token); if (headers != null) { for (Map.Entry<String, String> pair : headers.entrySet()) { conn.setRequestProperty(pair.getKey(), pair.getValue()); } } // Set the request parameters, if there are any if (parameters != null) { conn.setDoOutput(true); Writer wr = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); wr.write(urlencode(parameters)); wr.flush(); wr.close(); } // If we get a 401, retry once if (conn.getResponseCode() == 401 && !secondcall) { authenticate(); return call(verb, path, parameters, headers, true); } // The API response is in the input stream on success and the error stream on failure. BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (IOException e) { rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); String rawResponse = sb.toString(); if (503 == conn.getResponseCode()) throw new AthenahealthException("Service Temporarily Unavailable: " + rawResponse); if (!"application/json".equals(conn.getContentType())) throw new AthenahealthException("Expected application/json response, got " + conn.getContentType() + " instead." + " Content=" + rawResponse); // If it won't parse as an object, it'll parse as an array. Object response; try { response = new JSONObject(rawResponse); } catch (JSONException e) { try { response = new JSONArray(rawResponse); } catch (JSONException e2) { if (Boolean.getBoolean("com.athenahealth.api.dump-response-on-JSON-error")) { System.err.println("Server response code: " + conn.getResponseCode()); Map<String, List<String>> responseHeaders = conn.getHeaderFields(); for (Map.Entry<String, List<String>> header : responseHeaders.entrySet()) for (String value : header.getValue()) { if (null == header.getKey() || "".equals(header.getKey())) System.err.println("Status: " + value); else System.err.println(header.getKey() + "=" + value); } } throw new AthenahealthException( "Cannot parse response from server as JSONObject or JSONArray: " + rawResponse, e2); } } return response; } catch (MalformedURLException mue) { throw new AthenahealthException("Invalid URL", mue); } catch (IOException ioe) { throw new AthenahealthException("I/O error during call", ioe); } }
From source file:com.googlecode.jmxtrans.model.output.LibratoWriter.java
private void writeToLibrato(Server server, Query query, List<Result> results) { HttpURLConnection urlConnection = null; try {//from w ww . ja va 2s . c o m if (proxy == null) { urlConnection = (HttpURLConnection) url.openConnection(); } else { urlConnection = (HttpURLConnection) url.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(libratoApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication); urlConnection.setRequestProperty("User-Agent", httpUserAgent); serialize(server, query, results, urlConnection.getOutputStream()); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200) { logger.warn("Failure {}:'{}' to send result to Librato server '{}' with proxy {}, username {}", responseCode, urlConnection.getResponseMessage(), url, proxy, username); } if (logger.isTraceEnabled()) { StringWriter out = new StringWriter(); IOUtils.copy(urlConnection.getInputStream(), out); logger.trace(out.toString()); } } catch (Exception e) { logger.warn("Failure to send result to Librato server '{}' with proxy {}, username {}", url, proxy, username, e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); IOUtils.copy(in, NullOutputStream.NULL_OUTPUT_STREAM); IOUtils.closeQuietly(in); InputStream err = urlConnection.getErrorStream(); if (err != null) { IOUtils.copy(err, NullOutputStream.NULL_OUTPUT_STREAM); IOUtils.closeQuietly(err); } } catch (IOException e) { logger.warn("Exception flushing http connection", e); } } } }
From source file:org.jmxtrans.embedded.output.LibratoWriter.java
/** * Send given metrics to the Graphite server. */// ww w . j av a2s . c om @Override public void write(Iterable<QueryResult> results) { logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results); List<QueryResult> counters = new ArrayList<QueryResult>(); List<QueryResult> gauges = new ArrayList<QueryResult>(); for (QueryResult result : results) { if (METRIC_TYPE_GAUGE.equals(result.getType())) { gauges.add(result); } else if (METRIC_TYPE_COUNTER.equals(result.getType())) { counters.add(result); } else if (null == result.getType()) { logger.info("Unspecified type for result {}, export it as counter"); counters.add(result); } else { logger.info("Unsupported metric type '{}' for result {}, export it as counter", result.getType(), result); counters.add(result); } } HttpURLConnection urlConnection = null; try { if (proxy == null) { urlConnection = (HttpURLConnection) url.openConnection(); } else { urlConnection = (HttpURLConnection) url.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(libratoApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication); urlConnection.setRequestProperty("User-Agent", httpUserAgent); serialize(counters, gauges, urlConnection.getOutputStream()); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200) { exceptionCounter.incrementAndGet(); logger.warn("Failure {}:'{}' to send result to Librato server '{}' with proxy {}, user {}", responseCode, urlConnection.getResponseMessage(), url, proxy, user); } if (logger.isTraceEnabled()) { IoUtils2.copy(urlConnection.getInputStream(), System.out); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Failure to send result to Librato server '{}' with proxy {}, user {}", url, proxy, user, e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); IoUtils2.copy(in, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(in); InputStream err = urlConnection.getErrorStream(); if (err != null) { IoUtils2.copy(err, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(err); } } catch (IOException e) { logger.warn("Exception flushing http connection", e); } } } }
From source file:com.culvereq.vimp.networking.ConnectionHandler.java
public Vehicle addVehicle(TempVehicle vehicle) throws IOException, JSONException { URL requestURL = new URL(vehicleURL + "add"); HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection(); connection.setDoInput(true);// w w w .j a v a2s. c o m connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); String urlParameters = ""; urlParameters += "key=" + Globals.access_key; urlParameters += "&vehicle-name=" + vehicle.getName(); urlParameters += "&vehicle-type-id=" + vehicle.getType().getValue(); urlParameters += "&vehicle-make=" + vehicle.getMake(); urlParameters += "&vehicle-model" + vehicle.getModel(); urlParameters += "&vehicle-year" + vehicle.getYear(); urlParameters += "&vehicle-mileage" + vehicle.getMileage(); urlParameters += "&vehicle-vin" + vehicle.getVin(); urlParameters += "&vehicle-license-no" + vehicle.getLicenseNumber(); connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length); connection.setUseCaches(false); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(urlParameters); writer.flush(); writer.close(); int responseCode = connection.getResponseCode(); if (responseCode == 201) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject json = new JSONObject(response.toString()); return new Deserializer().deserializeVehicle(json, response.toString()); } else if (responseCode == 400) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); throw new IOException(response.toString()); } else { throw new IOException("Got response code: " + responseCode); } }
From source file:ai.api.AIDataService.java
protected String doTextRequest(@NonNull final String endpoint, @NonNull final String requestJson, @Nullable final Map<String, String> additionalHeaders) throws MalformedURLException, AIServiceException { HttpURLConnection connection = null; try {/*from ww w. j a v a 2s.c o m*/ final URL url = new URL(endpoint); final String queryData = requestJson; Log.d(TAG, "Request json: " + queryData); if (config.getProxy() != null) { connection = (HttpURLConnection) url.openConnection(config.getProxy()); } else { connection = (HttpURLConnection) url.openConnection(); } connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Bearer " + config.getApiKey()); connection.addRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.addRequestProperty("Accept", "application/json"); if (additionalHeaders != null) { for (final Map.Entry<String, String> entry : additionalHeaders.entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); } } connection.connect(); final BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.write(queryData, outputStream, Charsets.UTF_8); outputStream.close(); final InputStream inputStream = new BufferedInputStream(connection.getInputStream()); final String response = IOUtils.toString(inputStream, Charsets.UTF_8); inputStream.close(); return response; } catch (final IOException e) { if (connection != null) { try { final InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { final String errorString = IOUtils.toString(errorStream, Charsets.UTF_8); Log.d(TAG, "" + errorString); return errorString; } else { throw new AIServiceException("Can't connect to the api.ai service.", e); } } catch (final IOException ex) { Log.w(TAG, "Can't read error response", ex); } } Log.e(TAG, "Can't make request to the API.AI service. Please, check connection settings and API access token.", e); throw new AIServiceException( "Can't make request to the API.AI service. Please, check connection settings and API access token.", e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Retrieves the token from the token pool service. * * @param owner_id which is operator in Token Pool service * @return access token/* w ww . j av a 2 s . com*/ * @throws Exception */ private String getPoolAccessToken(String owner_id, String resourceURL) throws Exception { StringBuffer result = new StringBuffer(); HttpURLConnection poolConnection = null; URL requestUrl; try { requestUrl = new URL(resourceURL + URLEncoder.encode(owner_id, "UTF-8")); poolConnection = (HttpURLConnection) requestUrl.openConnection(); poolConnection.setDoOutput(true); poolConnection.setInstanceFollowRedirects(false); poolConnection.setRequestMethod("GET"); poolConnection.setRequestProperty("Accept", "application/json"); poolConnection.setUseCaches(false); InputStream input = null; if (poolConnection.getResponseCode() == 200) { input = poolConnection.getInputStream(); } else { input = poolConnection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(input)); String output; while ((output = br.readLine()) != null) { result.append(output); } br.close(); } catch (Exception e) { log.error("[TokenPoolRequestService ], getPoolAccessToken, " + e.getMessage()); return null; } finally { if (poolConnection != null) { poolConnection.disconnect(); } } return result.toString(); }