List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:org.dcm4che3.tool.wadouri.WadoURI.java
public void wado(WadoURI main) throws Exception { URL newUrl = new URL(setWadoRequestQueryParams(main, main.getUrl())); System.out.println(newUrl.toString()); HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection(); connection.setDoOutput(true);/*from w ww . j a v a 2 s . c o m*/ connection.setDoInput(true); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("GET"); if (main.getRequestTimeOut() != null) { connection.setConnectTimeout(Integer.valueOf(main.getRequestTimeOut())); connection.setReadTimeout(Integer.valueOf(main.getRequestTimeOut())); } connection.setUseCaches(false); int rspCode = connection.getResponseCode(); String rspMessage = connection.getResponseMessage(); InputStream in = connection.getInputStream(); String contentType = connection.getHeaderField("Content-Type"); String f = null; if (contentType.contains("application")) { if (contentType.contains("application/dicom+xml")) f = writeXML(in, main); else if (contentType.contains("application/pdf")) f = writeFile(in, main, ".pdf"); else //dicom f = writeFile(in, main, ".dcm"); } else if (contentType.contains("image")) { if (contentType.contains("image/jpeg")) f = writeFile(in, main, ".jpeg"); else if (contentType.contains("image/png")) f = writeFile(in, main, ".png"); else //gif f = writeFile(in, main, ".gif"); } else if (contentType.contains("text")) { if (contentType.contains("text/html")) { f = writeFile(in, main, ".html"); } else if (contentType.contains("text/rtf")) { f = writeFile(in, main, ".rtf"); } else if (contentType.contains("text/xml")) { f = writeFile(in, main, ".xml"); } else // text/plain f = writeFile(in, main, ".txt"); } this.response = new WadoURIResponse(rspCode, rspMessage, f); connection.disconnect(); }
From source file:fr.xebia.servlet.filter.XForwardedFilterTest.java
private void test302RedirectWithJetty(final String sendRedirectLocation, String expectedLocation, int httpsServerPortParameter) throws Exception { // SETUP/* w w w .j av a 2 s.c om*/ int port = 6666; Server server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); // mostly default configuration : enable "x-forwarded-proto" XForwardedFilter xforwardedFilter = new XForwardedFilter(); MockFilterConfig filterConfig = new MockFilterConfig(); filterConfig.addInitParameter(XForwardedFilter.PROTOCOL_HEADER_PARAMETER, "x-forwarded-proto"); filterConfig.addInitParameter(XForwardedFilter.HTTPS_SERVER_PORT_PARAMETER, String.valueOf(httpsServerPortParameter)); // Following is needed on ipv6 stacks.. filterConfig.addInitParameter(XForwardedFilter.INTERNAL_PROXIES_PARAMETER, InetAddress.getByName("localhost").getHostAddress()); xforwardedFilter.init(filterConfig); context.addFilter(new FilterHolder(xforwardedFilter), "/*", Handler.REQUEST); HttpServlet mockServlet = new HttpServlet() { private static final long serialVersionUID = 1L; @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect(sendRedirectLocation); } }; context.addServlet(new ServletHolder(mockServlet), "/test"); server.start(); try { // TEST HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test") .openConnection(); httpURLConnection.setInstanceFollowRedirects(false); String expectedRemoteAddr = "my-remote-addr"; httpURLConnection.addRequestProperty("x-forwarded-for", expectedRemoteAddr); httpURLConnection.addRequestProperty("x-forwarded-proto", "https"); // VALIDATE Assert.assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, httpURLConnection.getResponseCode()); String actualLocation = httpURLConnection.getHeaderField("Location"); assertEquals(expectedLocation, actualLocation); } finally { server.stop(); } }
From source file:org.sakaiproject.profile2.conversion.ProfileConverter.java
private void retrieveMainImage(String userUuid, String mainUrl) { InputStream inputStream = null; try {/*from w w w.jav a 2s. c o m*/ URL url = new URL(mainUrl); HttpURLConnection openConnection = (HttpURLConnection) url.openConnection(); openConnection.setReadTimeout(5000); openConnection.setConnectTimeout(5000); openConnection.setInstanceFollowRedirects(true); openConnection.connect(); int responseCode = openConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String mimeType = openConnection.getContentType(); inputStream = openConnection.getInputStream(); // Convert the image. byte[] imageMain = ProfileUtils.scaleImage(inputStream, ProfileConstants.MAX_IMAGE_XY, mimeType); //create resource ID String mainResourceId = sakaiProxy.getProfileImageResourcePath(userUuid, ProfileConstants.PROFILE_IMAGE_MAIN); log.info("Profile2 image converter: mainResourceId: " + mainResourceId); //save, if error, log and return. if (!sakaiProxy.saveFile(mainResourceId, userUuid, DEFAULT_FILE_NAME, mimeType, imageMain)) { log.error("Profile2 image importer: Saving main profile image failed."); } else { ci.setImage(imageMain); ci.setMimeType(mimeType); ci.setFileName(DEFAULT_FILE_NAME); ci.setMainResourceId(mainResourceId); ci.setNeedsSaving(true); } } else { log.warn("Failed to get good response for user " + userUuid + " for " + mainUrl + " got " + responseCode); } } catch (MalformedURLException e) { log.info("Invalid URL for user: " + userUuid + " of: " + mainUrl); } catch (IOException e) { log.warn("Failed to download image for: " + userUuid + " from: " + mainUrl + " error of: " + e.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ioe) { log.info("Failed to close input stream for request to: " + mainUrl); } } } }
From source file:com.apache.ivy.BasicURLHandler.java
public void upload(File source, URL dest, CopyProgressListener l) throws IOException { if (!"http".equals(dest.getProtocol()) && !"https".equals(dest.getProtocol())) { throw new UnsupportedOperationException("URL repository only support HTTP PUT at the moment"); }//www . j a v a 2 s. c o m // Install the IvyAuthenticator IvyAuthenticator.install(); HttpURLConnection conn = null; try { dest = normalizeToURL(dest); conn = (HttpURLConnection) dest.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("User-Agent", "Apache Ivy/1.0");// + Ivy.getIvyVersion()); conn.setRequestProperty("Content-type", "application/octet-stream"); conn.setRequestProperty("Content-length", Long.toString(source.length())); conn.setInstanceFollowRedirects(true); InputStream in = new FileInputStream(source); try { OutputStream os = conn.getOutputStream(); FileUtil.copy(in, os, l); } finally { try { in.close(); } catch (IOException e) { /* ignored */ } } validatePutStatusCode(dest, conn.getResponseCode(), conn.getResponseMessage()); } finally { disconnect(conn); } }
From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { URI uri = request.getURI();/*from www. ja va 2 s . c o m*/ // Is this a CONNECT request? if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod())) { response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE???? handleConnect(pathInContext, pathParams, request, response); return; } try { // Do we proxy this? URL url = isProxied(uri); if (url == null) { if (isForbidden(uri)) sendForbid(request, response, uri); return; } if (log.isDebugEnabled()) log.debug("PROXY URL=" + url); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getField(HttpFields.__Connection); if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close))) connectionHdr = null; // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getFieldNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0) continue; if (HttpFields.__ContentType.equals(hdr)) hasContent = true; Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr); } } } // Proxy headers if (!_anonymous) connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getField(HttpFields.__CacheControl); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection customizeConnection(pathInContext, pathParams, request, connection); try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { LogSupport.ignore(log, e); } InputStream proxy_in = null; // handler status codes etc. int code = HttpResponse.__500_Internal_Server_Error; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); response.setReason(http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { LogSupport.ignore(log, e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.removeField(HttpFields.__Date); response.removeField(HttpFields.__Server); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr) && (_chained || !_ProxyAuthHeaders.containsKey(hdr))) response.addField(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } if (!_anonymous) response.setField("Via", "1.1 (jetty)"); // Handled request.setHandled(true); if (proxy_in != null) IO.copy(proxy_in, response.getOutputStream()); } catch (Exception e) { log.warn(e.toString()); LogSupport.ignore(log, e); if (!response.isCommitted()) response.sendError(HttpResponse.__400_Bad_Request); } }
From source file:org.maikelwever.droidpile.backend.ApiConnecter.java
public String postData(ArrayList<NameValuePair> payload, String... data) throws IOException { if (data.length < 1) { throw new IllegalArgumentException("More than 1 argument is required."); }//from ww w . j a va2 s . c o m String url = this.baseUrl; String suffix = ""; for (String arg : data) { suffix += "/" + arg; } suffix += "/"; Log.d("droidpile", "URL we will call: " + url + suffix); url += suffix; URL uri = new URL(url); InputStreamReader is; HttpURLConnection con; if (url.startsWith("https")) { con = (HttpsURLConnection) uri.openConnection(); } else { con = (HttpURLConnection) uri.openConnection(); } String urlParameters = URLEncodedUtils.format(payload, ENCODING); con.setDoInput(true); con.setDoOutput(true); con.setInstanceFollowRedirects(false); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("charset", ENCODING); con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes(ENCODING).length)); con.setUseCaches(false); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); is = new InputStreamReader(con.getInputStream(), ENCODING); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while (read != null) { sb.append(read); read = br.readLine(); } String stringData = sb.toString(); con.disconnect(); return stringData; }
From source file:org.runnerup.export.RuntasticUploader.java
@Override public Status upload(SQLiteDatabase db, long mID) { Status s;// w w w .j av a 2 s.c o m if ((s = connect()) != Status.OK) { return s; } StringWriter writer = new StringWriter(); TCX tcx = new TCX(db); HttpURLConnection conn = null; try { Pair<String, Sport> res = tcx.exportWithSport(mID, writer); Sport sport = res.second; String filename = String.format("activity%s%d.tcx", Long.toString(Math.round(1000 * Math.random())), mID); String url = UPLOAD_URL + "?authenticity_token=" + URLEncode(authToken) + "&qqfile=" + filename; conn = (HttpURLConnection) new URL(url).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Host", "www.runtastic.com"); conn.addRequestProperty("X-Requested-With", "XMLHttpRequest"); conn.addRequestProperty("X-File-Name", filename); conn.addRequestProperty("Content-Type", "application/octet-stream"); addRequestHeaders(conn); OutputStream out = new BufferedOutputStream(conn.getOutputStream()); out.write(writer.toString().getBytes()); out.flush(); out.close(); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject ret = parse(in); getCookies(conn); if (ret == null || !ret.has("success") || !ret.getBoolean("success")) { System.out.println("ret: " + ret); throw new JSONException("Unexpected json return"); } String tmp = ret.getString("content"); final String name = "name='"; int i1 = tmp.indexOf(name); if (i1 < 0) { System.out.println("ret: " + ret); throw new JSONException("Unexpected json return"); } i1 += name.length(); int i2 = tmp.indexOf('\'', i1); String import_id = tmp.substring(i1, i2); System.out.println("import_id: " + import_id); conn.disconnect(); if (sport != null && sport != Sport.RUNNING && sport2runtasticMap.containsKey(sport)) { conn = (HttpURLConnection) new URL(UPDATE_SPORTS_TYPE).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.addRequestProperty("X-Requested-With", "XMLHttpRequest"); addRequestHeaders(conn); FormValues fv = new FormValues(); fv.put("authenticity_token", authToken); fv.put("data_import_id", import_id); fv.put("sport_type_id", sport2runtasticMap.get(sport).toString()); fv.put("user_id", userId.toString()); postData(conn, fv); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); System.out.println("code: " + responseCode + ", html: " + getFormValues(conn)); conn.disconnect(); } logout(); return Status.OK; } catch (IOException ex) { s.ex = ex; } catch (JSONException e) { s.ex = e; } if (s.ex != null) System.err.println("ex: " + s.ex); if (conn != null) conn.disconnect(); s = Status.ERROR; return s; }