List of usage examples for java.net HttpURLConnection HTTP_SEE_OTHER
int HTTP_SEE_OTHER
To view the source code for java.net HttpURLConnection HTTP_SEE_OTHER.
Click Source Link
From source file:org.jboss.aerogear.unifiedpush.SenderClient.java
/** * checks if the given status code is a redirect (301, 302 or 303 response status code) *//*from ww w . ja v a 2s.com*/ private static boolean isRedirect(int statusCode) { return statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_SEE_OTHER; }
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 w w w . ja v a2 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; }
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
public static String getRedirectUrl(REGION region) { String result = ""; switch (region) { case EU://from www . jav a 2 s . c o m result = amazonEuDomain; break; case USA: result = amazonUsaDomain; break; case ASIA: result = amazonAsiaDomain; break; } System.out.println("Trying to get real IP address of " + result); try { /* HttpHead headRequest = new HttpHead(result); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(headRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { String location = response.getHeaders("Location")[0].toString(); String redirecturl = location.replace("Location: ", ""); result = redirecturl; } */ URL url = new URL(result); HttpURLConnection httpGetCon = (HttpURLConnection) url.openConnection(); httpGetCon.setInstanceFollowRedirects(false); httpGetCon.setRequestMethod("GET"); httpGetCon.setConnectTimeout(5000); //set timeout to 5 seconds httpGetCon.setRequestProperty("User-Agent", USER_AGENT); int status = httpGetCon.getResponseCode(); System.out.println("code: " + status); if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) result = httpGetCon.getHeaderField("Location"); } catch (Exception e) { System.out.println("Exception is fired in redirector getter. error:" + e.getMessage()); e.printStackTrace(); } System.out.println("Real IP address is " + result); return result; }
From source file:vocab.VocabUtils.java
/** * Jena fails to load models in https with content negotiation. Therefore I do * the negotiation here directly// www. j a v a 2s .c om */ private static void doContentNegotiation(OntModel model, Vocabulary v, String accept, String serialization) { try { model.read(v.getUri(), null, serialization); } catch (Exception e) { try { System.out.println("Failed to read the ontology. Doing content negotiation"); URL url = new URL(v.getUri()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Accept", accept); int status = connection.getResponseCode(); if (status == HttpURLConnection.HTTP_SEE_OTHER || status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) { String newUrl = connection.getHeaderField("Location"); //v.setUri(newUrl); connection = (HttpURLConnection) new URL(newUrl).openConnection(); connection.setRequestProperty("Accept", accept); InputStream in = (InputStream) connection.getInputStream(); model.read(in, null, serialization); } } catch (Exception e2) { System.out.println("Failed to read the ontology"); } } }
From source file:ca.osmcanada.osvuploadr.JPMain.java
private String sendForm(String target_url, Map<String, String> arguments, String method, List<Cookie> cookielist) { try {/* w w w .j a v a2 s.c om*/ URL url = new URL(target_url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); //HttpURLConnection http = (HttpURLConnection)con; con.setRequestMethod(method); // PUT is another valid option con.setDoOutput(true); con.setInstanceFollowRedirects(false); String cookiestr = ""; if (cookielist != null) { if (cookielist.size() > 0) { for (Cookie cookie : cookielist) { if (!cookiestr.equals("")) { cookiestr += ";" + cookie.getName() + "=" + cookie.getValue(); } else { cookiestr += cookie.getName() + "=" + cookie.getValue(); } } con.setRequestProperty("Cookie", cookiestr); } } con.setReadTimeout(5000); StringJoiner sj = new StringJoiner("&"); for (Map.Entry<String, String> entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8); int length = out.length; con.setFixedLengthStreamingMode(length); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); con.setRequestProperty("Accept-Language", "en-us;"); con.connect(); try (OutputStream os = con.getOutputStream()) { os.write(out); os.close(); } boolean redirect = false; int status = con.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { String newURL = con.getHeaderField("Location"); String cookies = con.getHeaderField("Set-Cookie"); if (cookies == null) { cookies = cookiestr; } con = (HttpURLConnection) new URL(newURL).openConnection(); con.setRequestProperty("Cookie", cookies); } InputStream is = con.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti; while ((letti = is.read(buf)) > 0) baos.write(buf, 0, letti); String data = new String(baos.toByteArray(), Charset.forName("UTF-8")); con.disconnect(); return data; } catch (Exception ex) { Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } return ""; }
From source file:com.connectsdk.service.AirPlayService.java
@Override public void displayImage(final String url, String mimeType, String title, String description, String iconSrc, final LaunchListener listener) { Util.runInBackground(new Runnable() { @Override//from w w w .j av a2 s . co m public void run() { ResponseListener<Object> responseListener = new ResponseListener<Object>() { @Override public void onSuccess(Object response) { LaunchSession launchSession = new LaunchSession(); launchSession.setService(AirPlayService.this); launchSession.setSessionType(LaunchSessionType.Media); Util.postSuccess(listener, new MediaLaunchObject(launchSession, AirPlayService.this)); } @Override public void onError(ServiceCommandError error) { Util.postError(listener, error); } }; String uri = getRequestURL("photo"); byte[] payload = null; try { URL imagePath = new URL(url); HttpURLConnection connection = (HttpURLConnection) imagePath.openConnection(); connection.setInstanceFollowRedirects(true); connection.setDoInput(true); connection.connect(); int responseCode = connection.getResponseCode(); boolean redirect = (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER); if (redirect) { String newPath = connection.getHeaderField("Location"); URL newImagePath = new URL(newPath); connection = (HttpURLConnection) newImagePath.openConnection(); connection.setInstanceFollowRedirects(true); connection.setDoInput(true); connection.connect(); } InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); ByteArrayOutputStream stream = new ByteArrayOutputStream(); myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); payload = stream.toByteArray(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>( AirPlayService.this, uri, payload, responseListener); request.setHttpMethod(ServiceCommand.TYPE_PUT); request.send(); } }); }
From source file:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass, Object object, HashMap<String, String> headers) throws IOException { URL serverAddress;/* www . j a v a 2 s . c o m*/ HttpURLConnection connection; BufferedReader br; String result = ""; try { serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); connection.setInstanceFollowRedirects(false); boolean doOutput = doOutput(verb); connection.setDoOutput(doOutput); connection.setRequestMethod(method(verb)); connection.setRequestProperty("Authorization", headers.get("authorization")); connection.addRequestProperty("Accept", "application/json"); if (doOutput) { connection.addRequestProperty("Content-Length", "0"); OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream()); os.write(""); os.flush(); os.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { Link location = parseLocationLinkFromString(connection.getHeaderField("Location")); Link l = new Link("self", "/tokens", "GET", "", true); ArrayList<Link> links = new ArrayList<Link>(); links.add(l); links.add(location); ResponseData data = new ResponseData(); data.setLocation(location); data.setLinks(links); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("Authentication expired: " + connection.getResponseMessage()); if (retry && this.tokenData != null) { retry = false; this.tokenData = null; if (authenticate()) { System.out.println( "Reauthentication success, will continue with " + verb + " request on " + url); return sendRequestWithAddedHeaders(verb, url, tClass, object, headers); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + verb); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Server responded with internal server error, trying again in " + RETRY_WAIT_TIME + " msec."); try { retry = false; Thread.sleep(RETRY_WAIT_TIME); return sendRequestWithAddedHeaders(verb, url, tClass, object, headers); } catch (InterruptedException e) { } } else { System.out.println("Server responded with internal server error, please contact dev@nfleet.fi"); } 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; } return (T) gson.fromJson(result, tClass); }
From source file:org.sakaiproject.commons.tool.entityprovider.CommonsEntityProvider.java
@EntityCustomAction(action = "getUrlMarkup", viewKey = EntityView.VIEW_LIST) public ActionReturn getUrlMarkup(OutputStream outputStream, EntityView view, Map<String, Object> params) { String userId = getCheckedUser(); String urlString = (String) params.get("url"); if (StringUtils.isBlank(urlString)) { throw new EntityException("No url supplied", "", HttpServletResponse.SC_BAD_REQUEST); }//from w w w . j a v a2 s .co m try { CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); URL url = new URL(urlString); URLConnection c = url.openConnection(); if (c instanceof HttpURLConnection) { HttpURLConnection conn = (HttpURLConnection) c; conn.setRequestProperty("User-Agent", USER_AGENT); conn.setInstanceFollowRedirects(false); conn.connect(); String contentEncoding = conn.getContentEncoding(); String contentType = conn.getContentType(); int responseCode = conn.getResponseCode(); log.debug("Response code: {}", responseCode); int redirectCounter = 1; while ((responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_SEE_OTHER) && redirectCounter < 20) { String newUri = conn.getHeaderField("Location"); log.debug("{}. New URI: {}", responseCode, newUri); String cookies = conn.getHeaderField("Set-Cookie"); url = new URL(newUri); c = url.openConnection(); conn = (HttpURLConnection) c; conn.setInstanceFollowRedirects(false); conn.setRequestProperty("User-Agent", USER_AGENT); conn.setRequestProperty("Cookie", cookies); conn.connect(); contentEncoding = conn.getContentEncoding(); contentType = conn.getContentType(); responseCode = conn.getResponseCode(); log.debug("Redirect counter: {}", redirectCounter); log.debug("Response code: {}", responseCode); redirectCounter += 1; } if (contentType != null && (contentType.startsWith("text/html") || contentType.startsWith("application/xhtml+xml") || contentType.startsWith("application/xml"))) { String mimeType = contentType.split(";")[0].trim(); log.debug("mimeType: {}", mimeType); log.debug("encoding: {}", contentEncoding); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); String line = null; while ((line = reader.readLine()) != null) { writer.write(line); } return new ActionReturn(contentEncoding, mimeType, outputStream); } else { log.debug("Invalid content type {}. Throwing bad request ...", contentType); throw new EntityException("Url content type not supported", "", HttpServletResponse.SC_BAD_REQUEST); } } else { throw new EntityException("Url content type not supported", "", HttpServletResponse.SC_BAD_REQUEST); } } catch (MalformedURLException mue) { throw new EntityException("Invalid url supplied", "", HttpServletResponse.SC_BAD_REQUEST); } catch (IOException ioe) { throw new EntityException("Failed to download url contents", "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:io.sloeber.core.managers.Manager.java
/** * copy a url locally taking into account redirections * * @param url//from ww w . j a v a 2 s . c o m * @param localFile */ @SuppressWarnings("nls") private static void myCopy(URL url, File localFile) { try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8"); conn.addRequestProperty("User-Agent", "Mozilla"); conn.addRequestProperty("Referer", "google.com"); // normally, 3xx is redirect int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) Files.copy(new URL(conn.getHeaderField("Location")).openStream(), localFile.toPath(), REPLACE_EXISTING); } else { Files.copy(url.openStream(), localFile.toPath(), REPLACE_EXISTING); } } catch (Exception e) { Common.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to download url " + url, e)); } }
From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java
private String getIconUrlWithHttpRedirect(String imageUrl) throws IOException { URL url = new URL(imageUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int statusCode = conn.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_SEE_OTHER) { return conn.getHeaderField("Location"); } else {//w w w. j av a2 s. c om return imageUrl; } }