List of usage examples for java.net HttpURLConnection HTTP_BAD_GATEWAY
int HTTP_BAD_GATEWAY
To view the source code for java.net HttpURLConnection HTTP_BAD_GATEWAY.
Click Source Link
From source file:de.innovationgate.igutils.pingback.PingBackClient.java
private String determinePingBackURI(String targetURI) throws PingBackException { HttpClient client = WGFactory.getHttpClientFactory().createHttpClient(); GetMethod pingbackTargetGET = new GetMethod(targetURI); pingbackTargetGET.setFollowRedirects(false); try {/*w ww .ja v a 2 s .c o m*/ int responseCode = client.executeMethod(pingbackTargetGET); if (responseCode != HttpURLConnection.HTTP_OK) { if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { throw new PingBackException(PingBackException.ERROR_ACCESS_DENIED, "Access denied on target '" + targetURI + "'."); } else if (responseCode == HttpURLConnection.HTTP_BAD_GATEWAY) { throw new PingBackException(PingBackException.ERROR_UPSTREAM_SERVER_COMMUNICATION_ERROR, "Unable to determine ping back target for post. Get request on '" + targetURI + "' returned '" + responseCode + "'."); } else { throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET, "Unable to determine ping back target for post. Get request on '" + targetURI + "' returned '" + responseCode + "'."); } } Header header = pingbackTargetGET.getResponseHeader("X-Pingback"); if (header != null && header.getValues().length > 0) { // retrieve ping back url from header HeaderElement headerElement = header.getValues()[0]; return headerElement.getName(); } else { // retrieve ping back url from link tag // check for textual content checkTextualContentType(pingbackTargetGET); // retrieve input reader an try to find link tag InputStream sourceIn = pingbackTargetGET.getResponseBodyAsStream(); String searchTerm = "<link rel=\"pingback\" href=\""; if (sourceIn == null) { throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET, "TargetURL '" + targetURI + "' cannot be parsed for link tag."); } else { BufferedReader reader = new BufferedReader(new InputStreamReader( pingbackTargetGET.getResponseBodyAsStream(), pingbackTargetGET.getResponseCharSet())); String line = reader.readLine(); while (line != null) { String orgLine = line; line = line.toLowerCase(); int start = line.indexOf(searchTerm); if (start != -1) { if (start + searchTerm.length() <= line.length()) { start = start + searchTerm.length(); int end = line.indexOf("\"", start); if (end != -1) { String href = orgLine.substring(start, end); href = href.replaceAll("&", "&"); href = href.replaceAll("<", "<"); href = href.replaceAll(">", ">"); href = href.replaceAll(""", "\""); return href; } else { throw new PingBackException( PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET, "TargetURL '" + targetURI + "' returned an unparsable link-tag"); } } else { throw new PingBackException( PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET, "TargetURL '" + targetURI + "' returned an unparsable link-tag"); } } // if endof head reached - cancel search if (line.indexOf("</head>") != -1 || line.indexOf("<body>") != -1) { throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET, "TargetURL '" + targetURI + "' is not pingback-enabled."); } line = reader.readLine(); } throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET, "TargetURL '" + targetURI + "' is not pingback-enabled."); } } } catch (HttpException e) { throw new PingBackException(PingBackException.ERROR_GENERIC, "Unable to determine ping back target for post.", e); } catch (IOException e) { throw new PingBackException(PingBackException.ERROR_GENERIC, "Unable to determine ping back target for post.", e); } }
From source file:com.stackmob.example.TwilioSMS2.java
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { int responseCode = 0; String responseBody = ""; LoggerService logger = serviceProvider.getLoggerService(TwilioSMS.class); // TO phonenumber should be YOUR cel phone String toPhoneNumber = request.getParams().get("tophonenumber"); // FROM phonenumber should be one create in the twilio dashboard at twilio.com String fromPhoneNumber = "18572541790"; // text message you want to send String message = request.getParams().get("message"); if (toPhoneNumber == null || toPhoneNumber.isEmpty()) { logger.error("Missing phone number"); }/* w ww . j a v a2 s. c om*/ if (message == null || message.isEmpty()) { logger.error("Missing message"); } StringBuilder body = new StringBuilder(); body.append("To="); body.append(toPhoneNumber); body.append("&From="); body.append(fromPhoneNumber); body.append("&Body="); body.append(message); String url = "https://api.twilio.com/2010-04-01/Accounts/" + accountsid + "/SMS/Messages.json"; String pair = accountsid + ":" + accesstoken; // Base 64 Encode the accountsid/accesstoken String encodedString = new String("utf-8"); try { byte[] b = Base64.encodeBase64(pair.getBytes("utf-8")); encodedString = new String(b); } catch (Exception e) { logger.error(e.getMessage(), e); HashMap<String, String> errParams = new HashMap<String, String>(); errParams.put("error", "the auth header threw an exception: " + e.getMessage()); return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request } Header accept = new Header("Accept-Charset", "utf-8"); Header auth = new Header("Authorization", "Basic " + encodedString); Header content = new Header("Content-Type", "application/x-www-form-urlencoded"); Set<Header> set = new HashSet(); set.add(accept); set.add(content); set.add(auth); try { HttpService http = serviceProvider.getHttpService(); PostRequest req = new PostRequest(url, set, body.toString()); HttpResponse resp = http.post(req); responseCode = resp.getCode(); responseBody = resp.getBody(); } catch (TimeoutException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_BAD_GATEWAY; responseBody = e.getMessage(); } catch (AccessDeniedException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } catch (ServiceNotActivatedException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } Map<String, Object> map = new HashMap<String, Object>(); map.put("response_body", responseBody); return new ResponseToProcess(responseCode, map); }
From source file:com.stackmob.example.Stripe.java
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { int responseCode = 0; String responseBody = ""; LoggerService logger = serviceProvider.getLoggerService(Stripe.class); // AMOUNT should be a whole integer - ie 100 is 1 US dollar String amount = request.getParams().get("amount"); // CURRENCY - should be one of the supported currencies, please check STRIPE documentation. String currency = "usd"; // TOKEN - is returned when you submit the credit card information to stripe using // the Stripe JavaScript library. String token = request.getParams().get("token"); // DESCRIPTION - the description of the transaction String description = request.getParams().get("description"); if (token == null || token.isEmpty()) { logger.error("Token is missing"); }// w ww .java 2 s . c o m if (amount == null || amount.isEmpty()) { logger.error("Amount is missing"); } StringBuilder body = new StringBuilder(); body.append("amount="); body.append(amount); body.append("¤cy="); body.append(currency); body.append("&card="); body.append(token); body.append("&description="); body.append(description); String url = "https://api.stripe.com/v1/charges"; String pair = secretKey; //Base 64 Encode the secretKey String encodedString = new String("utf-8"); try { byte[] b = Base64.encodeBase64(pair.getBytes("utf-8")); encodedString = new String(b); } catch (Exception e) { logger.error(e.getMessage(), e); HashMap<String, String> errParams = new HashMap<String, String>(); errParams.put("error", "the auth header threw an exception: " + e.getMessage()); return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request } Header accept = new Header("Accept-Charset", "utf-8"); Header auth = new Header("Authorization", "Basic " + encodedString); Header content = new Header("Content-Type", "application/x-www-form-urlencoded"); Set<Header> set = new HashSet(); set.add(accept); set.add(content); set.add(auth); try { HttpService http = serviceProvider.getHttpService(); PostRequest req = new PostRequest(url, set, body.toString()); HttpResponse resp = http.post(req); responseCode = resp.getCode(); responseBody = resp.getBody(); } catch (TimeoutException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_BAD_GATEWAY; responseBody = e.getMessage(); } catch (AccessDeniedException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } catch (ServiceNotActivatedException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } Map<String, Object> map = new HashMap<String, Object>(); map.put("response_body", responseBody); return new ResponseToProcess(responseCode, map); }
From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java
private double getAvail(int code) { // There are too many options to list everything that is // successful. So, instead we are going to call out the // things that should be considered failure, everything else // is OK.//from w ww.j a v a 2s. c o m switch (code) { case HttpURLConnection.HTTP_BAD_REQUEST: case HttpURLConnection.HTTP_FORBIDDEN: case HttpURLConnection.HTTP_NOT_FOUND: case HttpURLConnection.HTTP_BAD_METHOD: case HttpURLConnection.HTTP_CLIENT_TIMEOUT: case HttpURLConnection.HTTP_CONFLICT: case HttpURLConnection.HTTP_PRECON_FAILED: case HttpURLConnection.HTTP_ENTITY_TOO_LARGE: case HttpURLConnection.HTTP_REQ_TOO_LONG: case HttpURLConnection.HTTP_INTERNAL_ERROR: case HttpURLConnection.HTTP_NOT_IMPLEMENTED: case HttpURLConnection.HTTP_UNAVAILABLE: case HttpURLConnection.HTTP_VERSION: case HttpURLConnection.HTTP_BAD_GATEWAY: case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: return Metric.AVAIL_DOWN; default: } if (hasCredentials()) { if (code == HttpURLConnection.HTTP_UNAUTHORIZED) { return Metric.AVAIL_DOWN; } } return Metric.AVAIL_UP; }
From source file:de.innovationgate.igutils.pingback.PingBackClient.java
/** * checks if the given sourceURI is reachable, has textual content and contains a link to the given target * if present the title of the sourceURI is returned * @param sourceURI - the sourceURI to check * @param targetURI - the targetURI to search as link * @throws PingBackException - thrown if check fails * @returns title of the sourceURI - null if not present or found *///w ww .ja v a 2 s . co m public String checkSourceURI(String sourceURI, String targetURI) throws PingBackException { HttpClient client = WGFactory.getHttpClientFactory().createHttpClient(); GetMethod sourceGET = new GetMethod(sourceURI); sourceGET.setFollowRedirects(false); try { int responseCode = client.executeMethod(sourceGET); if (responseCode != HttpURLConnection.HTTP_OK) { if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { throw new PingBackException(PingBackException.ERROR_ACCESS_DENIED, "Access denied on source uri '" + sourceURI + "'."); } else if (responseCode == HttpURLConnection.HTTP_BAD_GATEWAY) { throw new PingBackException(PingBackException.ERROR_UPSTREAM_SERVER_COMMUNICATION_ERROR, "Get request on source uri '" + sourceURI + "' returned '" + responseCode + "'."); } else { throw new PingBackException(PingBackException.ERROR_GENERIC, "Source uri is unreachable. Get request on source uri '" + sourceURI + "' returned '" + responseCode + "'."); } } checkTextualContentType(sourceGET); // search link to target in source InputStream sourceIn = sourceGET.getResponseBodyAsStream(); String searchTerm = targetURI.toLowerCase(); boolean linkFound = false; String title = null; if (sourceIn == null) { throw new PingBackException(PingBackException.ERROR_SOURCE_URI_HAS_NO_LINK, "Source uri contains no link to target '" + targetURI + "'."); } else { // first of all read response into a fix buffer of 2Mb - all further content will be ignored for doS-reason ByteArrayOutputStream htmlPageBuffer = new ByteArrayOutputStream(); inToOut(sourceGET.getResponseBodyAsStream(), htmlPageBuffer, 1024, documentSizeLimit); try { // search for title DOMParser parser = new DOMParser(); parser.parse(new InputSource(new ByteArrayInputStream(htmlPageBuffer.toByteArray()))); Document doc = parser.getDocument(); NodeList titleElements = doc.getElementsByTagName("title"); if (titleElements.getLength() > 0) { // retrieve first title Node titleNode = titleElements.item(0); title = titleNode.getFirstChild().getNodeValue(); } } catch (Exception e) { // ignore any parsing exception - title is just a goodie } // read line per line and search for link BufferedReader reader = new BufferedReader(new InputStreamReader( new ByteArrayInputStream(htmlPageBuffer.toByteArray()), sourceGET.getResponseCharSet())); String line = reader.readLine(); while (line != null) { line = line.toLowerCase(); if (line.indexOf(searchTerm) != -1) { linkFound = true; break; } line = reader.readLine(); } } if (!linkFound) { throw new PingBackException(PingBackException.ERROR_SOURCE_URI_HAS_NO_LINK, "Source uri '" + sourceURI + "' contains no link to target '" + targetURI + "'."); } else { return title; } } catch (HttpException e) { throw new PingBackException(PingBackException.ERROR_GENERIC, "Unable to check source uri '" + sourceURI + "'.", e); } catch (IOException e) { throw new PingBackException(PingBackException.ERROR_GENERIC, "Unable to check source uri '" + sourceURI + "'.", e); } }
From source file:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException { URL serverAddress;//from www . ja v a 2 s .c om BufferedReader br; String result = ""; HttpURLConnection connection = null; String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri(); try { String method = l.getMethod(); String type = l.getType(); serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); boolean doOutput = doOutput(method); connection.setDoOutput(doOutput); connection.setRequestMethod(method); connection.setInstanceFollowRedirects(false); if (method.equals("GET") && useMimeTypes) if (type == null || type.equals("")) { addMimeTypeAcceptToRequest(object, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } if (!useMimeTypes) connection.setRequestProperty("Accept", "application/json"); if (doOutput && useMimeTypes) { //this handles the case if the link is self made and the type field has not been set. if (type == null || type.equals("")) { addMimeTypeContentTypeToRequest(l, tClass, connection); addMimeTypeAcceptToRequest(l, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } if (!useMimeTypes) connection.setRequestProperty("Content-Type", "application/json"); if (tokenData != null) { connection.addRequestProperty("Authorization", tokenData.getTokenType() + " " + tokenData.getAccessToken()); } addVersionNumberToHeader(object, url, connection); if (method.equals("POST") || method.equals("PUT")) { String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object. connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + ""); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(json); osw.flush(); osw.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) { ResponseData data = new ResponseData(); Link link = parseLocationLinkFromString(connection.getHeaderField("Location")); link.setType(type); data.setLocation(link); connection.disconnect(); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println( "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate"); if (retry && this.tokenData != null) { this.tokenData = null; retry = false; if (authenticate()) { System.out.println("Reauthentication success, will continue with " + l.getMethod() + " request on " + l.getRel()); return sendRequest(l, tClass, object); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return (T) objectCache.getObject(url); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return (T) new ResponseData(); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + method); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println("Requst caused internal server error, please contact dev@nfleet.fi"); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) { if (retry) { System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println( "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later."); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } catch (SecurityException e) { throw e; } catch (IllegalArgumentException e) { throw e; } finally { assert connection != null; connection.disconnect(); } Object newEntity = gson.fromJson(result, tClass); objectCache.addUri(url, newEntity); return (T) newEntity; }