List of usage examples for java.net HttpURLConnection HTTP_MOVED_PERM
int HTTP_MOVED_PERM
To view the source code for java.net HttpURLConnection HTTP_MOVED_PERM.
Click Source Link
From source file:com.atlassian.launchpad.jira.whiteboard.WhiteboardTabPanel.java
@Override public List<IssueAction> getActions(Issue issue, User remoteUser) { List<IssueAction> messages = new ArrayList<IssueAction>(); //retrieve and validate url from custom field CustomField bpLinkField = ComponentAccessor.getCustomFieldManager() .getCustomFieldObjectByName(LAUNCHPAD_URL_FIELD_NAME); if (bpLinkField == null) { messages.add(new GenericMessageAction("\"" + LAUNCHPAD_URL_FIELD_NAME + "\" custom field not available. Cannot process Gerrit Review comments")); return messages; }/*from w ww .ja v a 2 s.c o m*/ Object bpURLFieldObj = issue.getCustomFieldValue(bpLinkField); if (bpURLFieldObj == null) { messages.add(new GenericMessageAction("\"" + LAUNCHPAD_URL_FIELD_NAME + "\" not provided. Please provide the Launchpad URL to view the whiteboard for this issue.")); return messages; } String bpURL = bpURLFieldObj.toString().trim(); if (bpURL.length() == 0) { messages.add( new GenericMessageAction("To view the Launchpad Blueprint for this issue please provide the " + LAUNCHPAD_URL_FIELD_NAME)); return messages; } if (!bpURL.matches(URL_REGEX)) { messages.add(new GenericMessageAction( "Launchpad URL not properly formatted. Please provide URL that appears as follows:<br/> https://blueprints.launchpad.net/devel/PROJECT NAME/+spec/BLUEPRINT NAME")); return messages; } String apiQuery = bpURL.substring( (bpURL.lastIndexOf(BASE_LAUNCHPAD_BLUEPRINT_HOST) + BASE_LAUNCHPAD_BLUEPRINT_HOST.length())); String url = BASE_LAUNCHPAD_API_URL + API_VERSION + apiQuery; try { //establish api connection URL obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); boolean redirect = false; // 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) redirect = true; } if (redirect) { // get redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); // open the new connection conn = (HttpURLConnection) new URL(newUrl).openConnection(); } //parse returned json BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer json = new StringBuffer(); while ((inputLine = in.readLine()) != null) { json.append(inputLine); } in.close(); //generate tab content JSONTokener tokener = new JSONTokener(json.toString()); JSONObject finalResult = new JSONObject(tokener); if (finalResult.has(WHITEBOARD) && finalResult.getString(WHITEBOARD).length() > 0) { messages.add(new GenericMessageAction( escapeHtml(finalResult.getString(WHITEBOARD)).replaceAll("\n", "<br/>"))); } else { messages.add(new GenericMessageAction("No whiteboard for this blueprint.")); } } catch (JSONException e) { // whiteboard JSON key not found e.printStackTrace(); } catch (FileNotFoundException e) { //unable to find the requested whiteboard messages.add(new GenericMessageAction( "Unable to find desired blueprint. Please check that the URL references the correct blueprint.")); return messages; } catch (IOException e) { // Exception in attempting to read from Launchpad API e.printStackTrace(); } return messages; }
From source file:httpget.HttpGet.java
private void obtainConnection() throws HttpGetException { try {// ww w.j a v a 2s . c om this.connection = (HttpURLConnection) url.openConnection(); this.connection.setInstanceFollowRedirects(true); this.connection.setReadTimeout(this.maxTimeout * 1000); if (this.requestHeaders != null) { Iterator i = this.requestHeaders.entrySet().iterator(); while (i.hasNext()) { Map.Entry pair = (Map.Entry) i.next(); this.connection.setRequestProperty((String) pair.getKey(), (String) pair.getValue()); } } this.connection.connect(); this.responseCode = this.connection.getResponseCode(); if (this.responseCode == HttpURLConnection.HTTP_SEE_OTHER || this.responseCode == HttpURLConnection.HTTP_MOVED_TEMP || this.responseCode == HttpURLConnection.HTTP_MOVED_PERM) { this.redirected_from[this.nRedirects++] = this.url.toString(); if (this.connection.getHeaderField("location") != null) this.setUrl(this.connection.getHeaderField("location")); else this.setUrl(this.redirectFromResponse()); this.obtainConnection(); } if (this.responseCode == HttpURLConnection.HTTP_FORBIDDEN) { throw new HttpGetException("Toegang verboden (403)", this.url.toString(), new Exception("Toegang verboden (403)"), redirected_from); } String mimeParts[] = this.connection.getContentType().split(";"); this.mimeType = mimeParts[0]; } catch (SocketTimeoutException e) { throw (new HttpGetException("Timeout bij ophalen gegevens", this.url.toString(), e, redirected_from)); } catch (IOException e) { throw (new HttpGetException("Probleem met verbinden", this.url.toString(), e, redirected_from)); } }
From source file:com.sonar.it.jenkins.orchestrator.container.JenkinsDownloader.java
private File downloadUrl(String url, File toFile) { try {/* ww w .jav a 2 s . c o m*/ FileUtils.forceMkdir(toFile.getParentFile()); HttpURLConnection conn; URL u = new URL(url); LOG.info("Download: " + u); // gets redirected multiple times, including from https -> http, so not done by Java while (true) { conn = (HttpURLConnection) u.openConnection(); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) { String newLocationHeader = conn.getHeaderField("Location"); LOG.info("Redirect: " + newLocationHeader); conn.disconnect(); u = new URL(newLocationHeader); continue; } break; } InputStream is = conn.getInputStream(); ByteStreams.copy(is, Files.asByteSink(toFile).openBufferedStream()); LOG.info("Downloaded to: " + toFile); return toFile; } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:org.apache.maven.wagon.providers.http.LightweightHttpWagon.java
public void fillInputData(InputData inputData) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { Resource resource = inputData.getResource(); String visitingUrl = buildUrl(resource.getName()); try {// w w w . ja va 2s . c o m List<String> visitedUrls = new ArrayList<String>(); for (int redirectCount = 0; redirectCount < MAX_REDIRECTS; redirectCount++) { if (visitedUrls.contains(visitingUrl)) { throw new TransferFailedException("Cyclic http redirect detected. Aborting! " + visitingUrl); } visitedUrls.add(visitingUrl); URL url = new URL(visitingUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(this.proxy); urlConnection.setRequestProperty("Accept-Encoding", "gzip"); if (!useCache) { urlConnection.setRequestProperty("Pragma", "no-cache"); } addHeaders(urlConnection); // TODO: handle all response codes int responseCode = urlConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_FORBIDDEN || responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new AuthorizationException("Access denied to: " + buildUrl(resource.getName())); } if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { visitingUrl = urlConnection.getHeaderField("Location"); continue; } InputStream is = urlConnection.getInputStream(); String contentEncoding = urlConnection.getHeaderField("Content-Encoding"); boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding); if (isGZipped) { is = new GZIPInputStream(is); } inputData.setInputStream(is); resource.setLastModified(urlConnection.getLastModified()); resource.setContentLength(urlConnection.getContentLength()); break; } } catch (MalformedURLException e) { throw new ResourceDoesNotExistException("Invalid repository URL: " + e.getMessage(), e); } catch (FileNotFoundException e) { throw new ResourceDoesNotExistException("Unable to locate resource in repository", e); } catch (IOException e) { StringBuilder message = new StringBuilder("Error transferring file: "); message.append(e.getMessage()); message.append(" from " + visitingUrl); if (getProxyInfo() != null && getProxyInfo().getHost() != null) { message.append(" with proxyInfo ").append(getProxyInfo().toString()); } throw new TransferFailedException(message.toString(), e); } }
From source file:org.fao.geonet.utils.GeonetHttpRequestFactoryTest.java
@Test public void testFollowsRedirects() throws Exception { final int port = 29484; InetSocketAddress address = new InetSocketAddress(port); HttpServer httpServer = HttpServer.create(address, 0); final Element expectedResponse = new Element("resource").addContent(new Element("id").setText("test")); HttpHandler finalHandler = new HttpHandler() { @Override//ww w. ja v a2s. c o m public void handle(HttpExchange exchange) throws IOException { byte[] response = Xml.getString(expectedResponse).getBytes(); exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length); exchange.getResponseBody().write(response); exchange.close(); } }; final String finalUrlPath = "/final.xml"; httpServer.createContext(finalUrlPath, finalHandler); HttpHandler permRedirectHandler = new HttpHandler() { @Override public void handle(HttpExchange exchange) throws IOException { byte[] response = finalUrlPath.getBytes(); exchange.getResponseHeaders().add("location", finalUrlPath); exchange.sendResponseHeaders(HttpURLConnection.HTTP_MOVED_PERM, response.length); exchange.getResponseBody().write(response); exchange.close(); } }; final String permUrlPath = "/permRedirect.xml"; httpServer.createContext(permUrlPath, permRedirectHandler); HttpHandler tempRedirectHandler = new HttpHandler() { @Override public void handle(HttpExchange exchange) throws IOException { byte[] response = finalUrlPath.getBytes(); exchange.getResponseHeaders().add("location", finalUrlPath); exchange.sendResponseHeaders(HttpURLConnection.HTTP_MOVED_TEMP, response.length); exchange.getResponseBody().write(response); exchange.close(); } }; final String tempUrlPath = "/tempRedirect.xml"; httpServer.createContext(tempUrlPath, tempRedirectHandler); try { httpServer.start(); XmlRequest xmlRequest = new GeonetHttpRequestFactory() .createXmlRequest(new URL("http://localhost:" + port + permUrlPath)); Element response = xmlRequest.execute(); assertEquals(Xml.getString(expectedResponse), Xml.getString(response)); xmlRequest = new GeonetHttpRequestFactory() .createXmlRequest(new URL("http://localhost:" + port + tempUrlPath)); response = xmlRequest.execute(); assertEquals(Xml.getString(expectedResponse), Xml.getString(response)); } finally { httpServer.stop(0); } }
From source file:fr.seeks.SuggestionProvider.java
public void setCursorOfQueryThrow(Uri uri, String query, MatrixCursor matrix) throws MalformedURLException, IOException { String url = getUrlFromKeywords(query); Log.v(TAG, "Query:" + url); String json = null;/* w w w . ja va2 s . c om*/ while (json == null) { HttpURLConnection connection = null; connection = (HttpURLConnection) (new URL(url)).openConnection(); try { connection.setDoOutput(true); connection.setChunkedStreamingMode(0); connection.setInstanceFollowRedirects(true); connection.connect(); int response = connection.getResponseCode(); if (response == HttpURLConnection.HTTP_MOVED_PERM || response == HttpURLConnection.HTTP_MOVED_TEMP) { Map<String, List<String>> list = connection.getHeaderFields(); for (Entry<String, List<String>> entry : list.entrySet()) { String value = ""; for (String s : entry.getValue()) { value = value + ";" + s; } Log.v(TAG, entry.getKey() + ":" + value); } // FIXME url = ""; return; } InputStream in = connection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(in)); StringBuilder builder = new StringBuilder(); String line; while ((line = r.readLine()) != null) { builder.append(line); } json = builder.toString(); /* * Log.v(TAG, "** JSON START **"); Log.v(TAG, json); Log.v(TAG, * "** JSON END **"); */ } catch (IOException e) { e.printStackTrace(); return; } finally { connection.disconnect(); } } JSONArray snippets; JSONObject object; JSONArray suggestions; Boolean show_snippets = mPrefs.getBoolean("show_snippets", false); if (show_snippets) { try { object = (JSONObject) new JSONTokener(json).nextValue(); snippets = object.getJSONArray("snippets"); } catch (JSONException e) { e.printStackTrace(); return; } Log.v(TAG, "Snippets found: " + snippets.length()); for (int i = 0; i < snippets.length(); i++) { JSONObject snip; try { snip = snippets.getJSONObject(i); matrix.newRow().add(i).add(snip.getString("title")).add(snip.getString("summary")) .add(snip.getString("title")).add(Intent.ACTION_SEND).add(snip.getString("url")); } catch (JSONException e) { e.printStackTrace(); continue; } } } else { try { object = (JSONObject) new JSONTokener(json).nextValue(); suggestions = object.getJSONArray("suggestions"); } catch (JSONException e) { e.printStackTrace(); return; } Log.v(TAG, "Suggestions found: " + suggestions.length()); for (int i = 0; i < suggestions.length(); i++) { try { matrix.newRow().add(i).add(suggestions.getString(i)).add("").add(suggestions.getString(i)) .add(Intent.ACTION_SEARCH).add(""); } catch (JSONException e) { e.printStackTrace(); continue; } } } getContext().getContentResolver().notifyChange(uri, null); }
From source file:uk.ac.ucl.excites.sapelli.collector.util.AsyncDownloader.java
private boolean download(String downloadUrl) { if (downloadUrl == null || downloadUrl.isEmpty()) { failure = new Exception("No URL given!"); return false; }//from ww w.j av a 2s.c o m //Log.d(getClass().getSimpleName(), "Download URL: " + downloadUrl); if (DeviceControl.isOnline(context)) { InputStream input = null; OutputStream output = null; try { URL url = new URL(downloadUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setInstanceFollowRedirects(false); // we handle redirects manually below (otherwise HTTP->HTTPS redirects don't work): conn.connect(); // Detect & follow redirects: int status = conn.getResponseCode(); //Log.d(getClass().getSimpleName(), "Response Code: " + status); if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { // follow redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); //Log.d(getClass().getSimpleName(), "Redirect to URL : " + newUrl); return download(newUrl); } // Getting file length final int fileLength = conn.getContentLength(); publishProgress(fileLength < 0 ? // when fileLength = -1 this means the server hasn't specified the file length -1 : // progressDialog will open and be set to indeterminate mode 0); // progressDialog will open and be set to 0 // Input stream to read file - with 8k buffer input = new BufferedInputStream(url.openStream(), 8192); // Output stream to write file output = new BufferedOutputStream(new FileOutputStream(downloadedFile)); byte data[] = new byte[1024]; int total = 0; int percentage = 0; int bytesRead; while ((bytesRead = input.read(data)) != -1) { // Complete % completion: if (fileLength > 0) // don't divide by 0 and only update progress if we know the fileLength (i.e. != -1) { int newPercentage = (int) ((total += bytesRead) / ((float) fileLength) * 100f); if (newPercentage != percentage) publishProgress(percentage = newPercentage); } // Write data to file... output.write(data, 0, bytesRead); } // Flush output: output.flush(); } catch (Exception e) { failure = e; return false; } finally { // Close streams: StreamHelpers.SilentClose(input); StreamHelpers.SilentClose(output); } //Log.d(getClass().getSimpleName(), "Download done"); return true; } else { failure = new Exception("The device is not online."); return false; } }
From source file:org.sociotech.communitymashup.source.mendeley.sdkadaption.AdaptedDocumentServiceImpl.java
protected String callGetForRedirectUrl(String apiUrl) { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); try {/*from w ww.jav a 2 s . com*/ HttpGet httpget = new HttpGet(apiUrl); if (!requestParameters.isEmpty()) { HttpParams params = httpget.getParams(); for (String name : requestParameters.keySet()) { params.setParameter(name, requestParameters.get(name)); } } for (String headerName : requestHeaders.keySet()) { httpget.addHeader(headerName, requestHeaders.get(headerName)); } signRequest(httpget); HttpResponse response = httpclient.execute(httpget); if (!((response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_MOVED_TEMP) || (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_MOVED_PERM) || (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_SEE_OTHER))) { return null; } // redirect location is in location header Header[] locationHeader = response.getHeaders("location"); if (locationHeader.length >= 1) { return locationHeader[0].getValue(); } } catch (IOException e) { throw new MendeleyException(e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources // httpclient.getConnectionManager().shutdown(); } return null; }
From source file:cc.arduino.utils.network.FileDownloader.java
private void downloadFile(boolean noResume) throws InterruptedException { RandomAccessFile file = null; try {//from w w w . java 2 s.co m // Open file and seek to the end of it file = new RandomAccessFile(outputFile, "rw"); initialSize = file.length(); if (noResume && initialSize > 0) { // delete file and restart downloading Files.delete(outputFile.toPath()); initialSize = 0; } file.seek(initialSize); setStatus(Status.CONNECTING); Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(downloadUrl.toURI()); if ("true".equals(System.getProperty("DEBUG"))) { System.err.println("Using proxy " + proxy); } HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(proxy); connection.setRequestProperty("User-agent", userAgent); if (downloadUrl.getUserInfo() != null) { String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", auth); } connection.setRequestProperty("Range", "bytes=" + initialSize + "-"); connection.setConnectTimeout(5000); setDownloaded(0); // Connect connection.connect(); int resp = connection.getResponseCode(); if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) { URL newUrl = new URL(connection.getHeaderField("Location")); proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(newUrl.toURI()); // open the new connnection again connection = (HttpURLConnection) newUrl.openConnection(proxy); connection.setRequestProperty("User-agent", userAgent); if (downloadUrl.getUserInfo() != null) { String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", auth); } connection.setRequestProperty("Range", "bytes=" + initialSize + "-"); connection.setConnectTimeout(5000); connection.connect(); resp = connection.getResponseCode(); } if (resp < 200 || resp >= 300) { throw new IOException("Received invalid http status code from server: " + resp); } // Check for valid content length. long len = connection.getContentLength(); if (len >= 0) { setDownloadSize(len); } setStatus(Status.DOWNLOADING); synchronized (this) { stream = connection.getInputStream(); } byte buffer[] = new byte[10240]; while (status == Status.DOWNLOADING) { int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); setDownloaded(getDownloaded() + read); if (Thread.interrupted()) { file.close(); throw new InterruptedException(); } } if (getDownloadSize() != null) { if (getDownloaded() < getDownloadSize()) throw new Exception("Incomplete download"); } setStatus(Status.COMPLETE); } catch (InterruptedException e) { setStatus(Status.CANCELLED); // lets InterruptedException go up to the caller throw e; } catch (SocketTimeoutException e) { setStatus(Status.CONNECTION_TIMEOUT_ERROR); setError(e); } catch (Exception e) { setStatus(Status.ERROR); setError(e); } finally { IOUtils.closeQuietly(file); synchronized (this) { IOUtils.closeQuietly(stream); } } }
From source file:me.philio.ghost.ui.LoginUrlFragment.java
@Override public void failure(RetrofitError error) { int status = 0; if (error.getResponse() != null) { status = error.getResponse().getStatus(); }//from w w w. java 2s . c om switch (status) { case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: // Got a redirect Log.d(TAG, "Url is a redirect!"); // Get the redirect url and examine to attempt to provide most // useful error message String redirectUrl = null; for (Header header : error.getResponse().getHeaders()) { if (header.getName() == null) { continue; } if (header.getName().equals("Location")) { String value = header.getValue(); if (value.endsWith("/ghost/api/v0.1/")) { redirectUrl = value.substring(0, value.length() - 16); } else { redirectUrl = value; } } } if (redirectUrl != null) { mEditUrl.setError(getString(R.string.error_redirect_url_to, redirectUrl)); } else { mEditUrl.setError(getString(R.string.error_redirect_url)); } break; case HttpURLConnection.HTTP_UNAUTHORIZED: // Got a 401 so could be a blog, check that the response is JSON Object body = error.getBodyAs(JsonObject.class); if (body != null && body instanceof JsonObject) { Log.d(TAG, "Url looks good!"); mListener.onValidUrl(mBlogUrl); } else { mEditUrl.setError(getString(R.string.error_invalid_url)); } break; default: mEditUrl.setError(getString(R.string.error_invalid_url)); break; } mBtnValidate.setEnabled(true); ((LoginActivity) getActivity()).setToolbarProgressBarVisibility(false); }