List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:com.newrelic.agent.Obfuscation.Proguard.java
private void sendMapping(String mapping) /* */ {//from w w w .j ava 2s . c o m /* 138 */ StringBuilder requestBody = new StringBuilder(); /* */ /* 140 */ requestBody.append("proguard=" + URLEncoder.encode(mapping)); /* 141 */ requestBody.append("&buildId=" + NewRelicClassVisitor.getBuildId()); /* */ try /* */ { /* 144 */ String host = "mobile-symbol-upload.newrelic.com"; /* 145 */ if (this.mappingApiHost != null) { /* 146 */ host = this.mappingApiHost; /* */ } /* */ /* 149 */ URL url = new URL("https://" + host + "/symbol"); /* 150 */ HttpURLConnection connection = (HttpURLConnection) url.openConnection(); /* */ /* 152 */ connection.setUseCaches(false); /* 153 */ connection.setDoOutput(true); /* 154 */ connection.setRequestMethod("POST"); /* 155 */ connection.setRequestProperty("X-APP-LICENSE-KEY", this.licenseKey); /* 156 */ connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); /* 157 */ connection.setRequestProperty("Content-Length", Integer.toString(requestBody.length())); /* */ /* 159 */ DataOutputStream request = new DataOutputStream(connection.getOutputStream()); /* 160 */ request.writeBytes(requestBody.toString()); /* 161 */ request.close(); /* */ /* 163 */ int responseCode = connection.getResponseCode(); /* 164 */ if (responseCode == 400) { /* 165 */ InputStream inputStream = connection.getErrorStream(); /* 166 */ String response = convertStreamToString(inputStream); /* 167 */ this.log .error("Unable to send your ProGuard mapping.txt to New Relic as the params are incorrect: " + response); /* 168 */ this.log .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually."); /* 169 */ } else if (responseCode > 400) { /* 170 */ InputStream inputStream = connection.getErrorStream(); /* 171 */ String response = convertStreamToString(inputStream); /* 172 */ this.log.error("Unable to send your ProGuard mapping.txt to New Relic - received status " + responseCode + ": " + response); /* 173 */ this.log .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually."); /* */ } /* */ /* 176 */ this.log.info("Successfully sent mapping.txt to New Relic."); /* */ /* 178 */ connection.disconnect(); /* */ } catch (IOException e) { /* 180 */ this.log.error("Encountered an error while uploading your ProGuard mapping to New Relic", e); /* 181 */ this.log .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually."); /* */ } /* */ }
From source file:com.hpe.application.automation.tools.common.rest.RestClient.java
/** * @param connection/*from w w w .j a va 2s . com*/ * that is already connected to its url with an http request, and that should contain * a response for us to retrieve * @return a response from the server to the previously submitted http request */ private Response retrieveHtmlResponse(HttpURLConnection connection) { Response ret = new Response(); try { ret.setStatusCode(connection.getResponseCode()); ret.setHeaders(connection.getHeaderFields()); } catch (Exception cause) { throw new SSEException(cause); } InputStream inputStream; // select the source of the input bytes, first try 'regular' input try { inputStream = connection.getInputStream(); } // if the connection to the server somehow failed, for example 404 or 500, // con.getInputStream() will throw an exception, which we'll keep. // we'll also store the body of the exception page, in the response data. */ catch (Exception e) { inputStream = connection.getErrorStream(); ret.setFailure(e); } // this takes data from the previously set stream (error or input) // and stores it in a byte[] inside the response ByteArrayOutputStream container = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int read; try { while ((read = inputStream.read(buf, 0, 1024)) > 0) { container.write(buf, 0, read); } ret.setData(container.toByteArray()); } catch (Exception ex) { throw new SSEException(ex); } return ret; }
From source file:com.baseproject.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());// w ww .j a v a2 s . co m map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException(Util.buildHttpErrorMsg("failed", -1, "URL blocked by rewriter: " + url)); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); // if (responseCode == -1) { // // -1 is returned by getResponseCode() if the response code could not be retrieved. // // Signal to the caller that something was wrong with the connection. // throw new IOException("Could not retrieve response code from HttpUrlConnection."); // } if (responseCode != HttpStatus.SC_NOT_MODIFIED && responseCode != HttpURLConnection.HTTP_OK) { InputStream in = null; try { in = connection.getErrorStream(); } catch (Exception e) { e.printStackTrace(); } if (in == null) { throw new IOException(Util.buildHttpErrorMsg("failed", responseCode, "unknown")); } else { throw new IOException(Util.convertStreamToString(in)); } } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { if (header.getKey().equals("Set-Cookie")) { List<String> cookieValue = header.getValue(); for (String c : cookieValue) { Header h = new BasicHeader(header.getKey(), c); response.addHeader(h); } } else { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } } return response; }
From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.TestRMWebServicesDelegationTokenAuthentication.java
@Test public void testDelegationTokenAuth() throws Exception { final String token = getDelegationToken("test"); ApplicationSubmissionContextInfo app = new ApplicationSubmissionContextInfo(); String appid = "application_123_0"; app.setApplicationId(appid);//from w ww. j a v a2s . c o m String requestBody = getMarshalledAppInfo(app); URL url = new URL("http://localhost:8088/ws/v1/cluster/apps"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); setupConn(conn, "POST", "application/xml", requestBody); // this should fail with unauthorized because only // auth is kerberos or delegation token try { conn.getInputStream(); fail("we should not be here"); } catch (IOException e) { assertEquals(Status.UNAUTHORIZED.getStatusCode(), conn.getResponseCode()); } conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty(delegationTokenHeader, token); setupConn(conn, "POST", MediaType.APPLICATION_XML, requestBody); // this should not fail try { conn.getInputStream(); } catch (IOException ie) { InputStream errorStream = conn.getErrorStream(); String error = ""; BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader(errorStream, "UTF8")); for (String line; (line = reader.readLine()) != null;) { error += line; } reader.close(); errorStream.close(); fail("Response " + conn.getResponseCode() + "; " + error); } boolean appExists = rm.getRMContext().getRMApps().containsKey(ApplicationId.fromString(appid)); assertTrue(appExists); RMApp actualApp = rm.getRMContext().getRMApps().get(ApplicationId.fromString(appid)); String owner = actualApp.getUser(); assertEquals("client", owner); }
From source file:alluxio.rest.TestCase.java
/** * Runs the test case and returns the output. *///from w ww .java 2 s . c o m public String call() throws Exception { HttpURLConnection connection = (HttpURLConnection) createURL().openConnection(); connection.setRequestMethod(mMethod); if (mOptions.getInputStream() != null) { connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/octet-stream"); ByteStreams.copy(mOptions.getInputStream(), connection.getOutputStream()); } if (mOptions.getBody() != null) { connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); ObjectMapper mapper = new ObjectMapper(); // make sure that serialization of empty objects does not fail mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); OutputStream os = connection.getOutputStream(); os.write(mapper.writeValueAsString(mOptions.getBody()).getBytes()); os.close(); } connection.connect(); if (connection.getResponseCode() != Response.Status.OK.getStatusCode()) { InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { Assert.fail("Request failed: " + IOUtils.toString(errorStream)); } Assert.fail("Request failed with status code " + connection.getResponseCode()); } return getResponse(connection); }
From source file:com.trk.aboutme.facebook.Response.java
@SuppressWarnings("resource") static List<Response> fromHttpConnection(HttpURLConnection connection, RequestBatch requests) { InputStream stream = null;/* w ww .j a v a 2 s.c o m*/ FileLruCache cache = null; String cacheKey = null; if (requests instanceof CacheableRequestBatch) { CacheableRequestBatch cacheableRequestBatch = (CacheableRequestBatch) requests; cache = getResponseCache(); cacheKey = cacheableRequestBatch.getCacheKeyOverride(); if (Utility.isNullOrEmpty(cacheKey)) { if (requests.size() == 1) { // Default for single requests is to use the URL. cacheKey = requests.get(0).getUrlForSingleRequest(); } else { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_CACHE_TAG, "Not using cache for cacheable request because no key was specified"); } } // Try loading from cache. If that fails, load from the network. if (!cacheableRequestBatch.getForceRoundTrip() && cache != null && !Utility.isNullOrEmpty(cacheKey)) { try { stream = cache.get(cacheKey); if (stream != null) { return createResponsesFromStream(stream, null, requests, true); } } catch (FacebookException exception) { // retry via roundtrip below } catch (JSONException exception) { } catch (IOException exception) { } finally { Utility.closeQuietly(stream); } } } // Load from the network, and cache the result if not an error. try { if (connection.getResponseCode() >= 400) { stream = connection.getErrorStream(); } else { stream = connection.getInputStream(); if ((cache != null) && (cacheKey != null) && (stream != null)) { InputStream interceptStream = cache.interceptAndPut(cacheKey, stream); if (interceptStream != null) { stream = interceptStream; } } } return createResponsesFromStream(stream, connection, requests, false); } catch (FacebookException facebookException) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", facebookException); return constructErrorResponses(requests, connection, facebookException); } catch (JSONException exception) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception); return constructErrorResponses(requests, connection, new FacebookException(exception)); } catch (IOException exception) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception); return constructErrorResponses(requests, connection, new FacebookException(exception)); } finally { Utility.closeQuietly(stream); } }
From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java
/** * Likes video with given position.//from w w w .j a va 2 s . c o m */ public static boolean like(final String innerurl) { try { String url = "https://graph.facebook.com/me/og.likes"; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("Accept-Encoding", "identity"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; U; " + "CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 " + "(KHTML, like Gecko) Version/4.0.5 Mobile/8A293 " + "Safari/6531.22.7"); conn.setRequestMethod("POST"); conn.setDoOutput(true); StringBuilder sb = new StringBuilder(); sb.append("method="); sb.append("POST"); sb.append("&"); sb.append("access_token="); sb.append(Authorization.getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK).getAccessToken()); sb.append("&"); sb.append("object="); sb.append(URLEncoder.encode(innerurl)); String params = sb.toString(); conn.getOutputStream().write(params.getBytes("UTF-8")); String response = ""; try { InputStream in = conn.getInputStream(); StringBuilder sbr = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { sbr.append(line); } in.close(); response = sbr.toString(); } catch (FileNotFoundException e) { InputStream in = conn.getErrorStream(); StringBuilder sbr = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { sbr.append(line); } in.close(); response = sbr.toString(); Log.e(TAG, "response = " + response); } try { JSONObject obj = new JSONObject(response); obj.getString("id"); return true; } catch (JSONException jSONEx) { // fb // // ? ? ? ? ? conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("Accept-Encoding", "identity"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; U; " + "CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 " + "(KHTML, like Gecko) Version/4.0.5 Mobile/8A293 " + "Safari/6531.22.7"); conn.setRequestMethod("POST"); conn.setDoOutput(true); sb = new StringBuilder(); sb.append("method="); sb.append("POST"); sb.append("&"); sb.append("access_token="); sb.append(Authorization.getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK) .getAccessToken()); sb.append("&"); sb.append("object="); sb.append(URLEncoder.encode(innerurl)); params = sb.toString(); conn.getOutputStream().write(params.getBytes("UTF-8")); try { InputStream in = conn.getInputStream(); StringBuilder sbr = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { sbr.append(line); } in.close(); response = sbr.toString(); Log.e(TAG, "response2 = " + response); try { JSONObject obj = new JSONObject(response); obj.getString("id"); return true; } catch (JSONException e) { return false; } } catch (FileNotFoundException e) { return false; } } } catch (MalformedURLException mURLEx) { Log.d("", ""); return false; } catch (IOException iOEx) { Log.d("", ""); return false; } catch (Exception ex) { Log.d("", ""); return false; } }
From source file:com.aylien.textapi.HttpSender.java
public String post(String url, Map<String, String> parameters, Map<String, String> headers) throws IOException, TextAPIException { try {//from w w w .j av a 2 s. com HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); for (Map.Entry<String, String> header : headers.entrySet()) { connection.setRequestProperty(header.getKey(), header.getValue()); } connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", USER_AGENT); StringBuilder payload = new StringBuilder(); for (Map.Entry<String, String> e : parameters.entrySet()) { if (payload.length() > 0) { payload.append('&'); } payload.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=') .append(URLEncoder.encode(e.getValue(), "UTF-8")); } OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(payload.toString()); writer.close(); responseHeaders = connection.getHeaderFields(); InputStream inputStream = connection.getResponseCode() == 200 ? connection.getInputStream() : connection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); if (connection.getResponseCode() >= 300) { extractTextAPIError(response.toString()); } return response.toString(); } catch (MalformedURLException e) { throw new IOException(e); } }
From source file:ccs_server.Sender.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, String, int)} for more info. * * @return result of the post, or {@literal null} if the GCM service was * unavailable or any network exception caused the request to fail. * * @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status. * @throws IllegalArgumentException if registrationId is {@literal null}. *///w w w . java 2 s . c om public Result sendNoRetry(Message message, String registrationId) throws IOException { StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId); Boolean delayWhileIdle = message.isDelayWhileIdle(); if (delayWhileIdle != null) { addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0"); } Boolean dryRun = message.isDryRun(); if (dryRun != null) { addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } String restrictedPackageName = message.getRestrictedPackageName(); if (restrictedPackageName != null) { addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName); } Integer timeToLive = message.getTimeToLive(); if (timeToLive != null) { addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive)); } for (Entry<String, String> entry : message.getData().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key == null || value == null) { logger.warning("Ignoring payload entry thas has null: " + entry); } else { key = PARAM_PAYLOAD_PREFIX + key; addParameter(body, key, URLEncoder.encode(value, UTF8)); } } String requestBody = body.toString(); logger.finest("Request body: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } if (status / 100 == 5) { logger.fine("GCM service is unavailable (status " + status + ")"); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("Plain post error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } else { try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "Exception reading response: ", e); // return null so it can retry return null; } } String[] lines = responseBody.split("\n"); if (lines.length == 0 || lines[0].equals("")) { throw new IOException("Received empty response from GCM service."); } String firstLine = lines[0]; String[] responseParts = split(firstLine); String token = responseParts[0]; String value = responseParts[1]; if (token.equals(TOKEN_MESSAGE_ID)) { Builder builder = new Result.Builder().messageId(value); // check for canonical registration id if (lines.length > 1) { String secondLine = lines[1]; responseParts = split(secondLine); token = responseParts[0]; value = responseParts[1]; if (token.equals(TOKEN_CANONICAL_REG_ID)) { builder.canonicalRegistrationId(value); } else { logger.warning("Invalid response from GCM: " + responseBody); } } Result result = builder.build(); if (logger.isLoggable(Level.FINE)) { logger.fine("Message created succesfully (" + result + ")"); } return result; } else if (token.equals(TOKEN_ERROR)) { return new Result.Builder().errorCode(value).build(); } else { throw new IOException("Invalid response from GCM: " + responseBody); } }
From source file:com.yohanliyanage.jenkins.plugins.sparkdeploy.deployer.DeploymentManager.java
@SuppressWarnings("unchecked") private Map<String, Object> invokeUrl(String method, URL url, String payload) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setRequestProperty("Accept", "application/json"); if (payload != null) { if (verbose) { logger.println("[Spark-Deployer] VERBOSE : Invoking URL: " + method + " " + url.toString() + " with payload : \n" + payload); }/*from w w w . j ava 2 s .co m*/ connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); OutputStream os = connection.getOutputStream(); os.write(payload.getBytes()); os.flush(); } else { if (verbose) { logger.println("[Spark-Deployer] VERBOSE : Invoking URL " + method + " " + url.toString()); } } InputStream responseStream; if (isSuccessResponseCode(connection.getResponseCode())) { // 2xx - Success responseStream = connection.getInputStream(); } else { responseStream = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(responseStream)); StringBuilder response = new StringBuilder(); String line; while ((line = br.readLine()) != null) { response.append(line).append(System.lineSeparator()); } if (verbose) { logger.println("[Spark-Deployer] VERBOSE : Response from Spark : \n" + response); } if (!isSuccessResponseCode(connection.getResponseCode())) { throw new RuntimeException("Operation Failed. Response is " + connection.getResponseCode() + " : " + connection.getResponseMessage()); } return (Map) mapper.readValue(response.toString(), HashMap.class); }