List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:export.GarminUploader.java
@Override public Status connect() { Status s = Status.NEED_AUTH;//from w w w .ja v a 2 s. co m s.authMethod = Uploader.AuthMethod.USER_PASS; if (username == null || password == null) { return s; } if (isConnected) { return Status.OK; } Exception ex = null; HttpURLConnection conn = null; logout(); try { conn = (HttpURLConnection) new URL(CHOOSE_URL).openConnection(); conn.setInstanceFollowRedirects(false); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); System.err.println("GarminUploader.connect() CHOOSE_URL => code: " + responseCode + ", msg: " + amsg); if (responseCode == 200) { return connectOld(); } else if (responseCode == 302) { return connectNew(); } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } if (conn != null) conn.disconnect(); s = Uploader.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java
public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri, String servletPath, String proxyPath) throws ServletException, IOException { //System.out.println("LOAD "+uri); //System.out.println("LOAD "+proxyPath); if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else {//from w w w . ja v a 2 s .co m URL url = new URL(uri); 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.getHeader("Connection"); if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; } // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-type".equals(lhdr)) hasContent = true; Enumeration vals = request.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getHeader("Cache-Control"); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IOUtils.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { e.printStackTrace(); } InputStream proxy_in = null; // handler status codes etc. int code = 500; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code, http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { e.printStackTrace(); proxy_in = http.getErrorStream(); } } // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) { if (hdr.equalsIgnoreCase("Location")) { val = Rewriter.translateCleanUrl(val, servletPath, proxyPath); } response.addHeader(hdr, val); } h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } boolean isGzipped = connection.getContentEncoding() != null && connection.getContentEncoding().contains("gzip"); response.addHeader("Via", "1.1 (jetty)"); // boolean process = connection.getContentType() == null // || connection.getContentType().isEmpty() // || connection.getContentType().contains("html"); boolean process = connection.getContentType() != null && connection.getContentType().contains("text"); if (proxy_in != null) { if (!process) { IOUtils.copy(proxy_in, response.getOutputStream()); proxy_in.close(); } else { InputStream in; if (isGzipped && proxy_in != null && proxy_in.available() > 0) { in = new GZIPInputStream(proxy_in); } else { in = proxy_in; } ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream(); IOUtils.copy(in, byteArrOS); in.close(); if (in != proxy_in) proxy_in.close(); String charset = response.getCharacterEncoding(); if (charset == null || charset.isEmpty()) { charset = "ISO-8859-1"; } String originalContent = new String(byteArrOS.toByteArray(), charset); byteArrOS.close(); return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped); } } } return null; }
From source file:org.ringside.client.BaseRequestHandler.java
public URLConnection connectToServer(ApiMethod method, Parameters params, Context context) throws Exception { // are we ensured that our protocol is always one of either http or https // build our HTTP (or HTTPS) connection? this method assumes so CharSequence postString = params.implode('&'); HttpURLConnection conn = (HttpURLConnection) context.getServerAddress().openConnection(); conn.setAllowUserInteraction(false); conn.setConnectTimeout(60000);/*from w w w . ja v a 2 s . c o m*/ conn.setReadTimeout(60000); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", USER_AGENT); conn.setRequestProperty("Content-length", Integer.toString(postString.length())); conn.setInstanceFollowRedirects(true); conn.setRequestMethod("POST"); // connect to the server and write the parameters to the output conn.connect(); conn.getOutputStream().write(postString.toString().getBytes()); return conn; }
From source file:org.pocketcampus.plugin.moodle.server.old.MoodleServiceImpl.java
public TequilaToken getTequilaTokenForMoodle() throws TException { System.out.println("getTequilaTokenForMoodle"); try {// w w w.jav a2 s.c om HttpURLConnection conn2 = (HttpURLConnection) new URL("http://moodle.epfl.ch/auth/tequila/index.php") .openConnection(); conn2.setInstanceFollowRedirects(false); conn2.getInputStream(); URL url = new URL(conn2.getHeaderField("Location")); MultiMap<String> params = new MultiMap<String>(); UrlEncoded.decodeTo(url.getQuery(), params, "UTF-8"); TequilaToken teqToken = new TequilaToken(params.getString("requestkey")); Cookie cookie = new Cookie(); for (String header : conn2.getHeaderFields().get("Set-Cookie")) { cookie.addFromHeader(header); } teqToken.setLoginCookie(cookie.cookie()); return teqToken; } catch (IOException e) { e.printStackTrace(); throw new TException("Failed to getTequilaToken from upstream server"); } }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.util.Fetcher.java
protected HttpURLConnection getConnection(final String url, final String data, final String requestMethod, final long lastFetchTime) throws IOException { String method = GET_STR;//from w w w . j a v a2 s . co m if (requestMethod != null) { method = requestMethod; } LOGGER.info(method + "ing: " + url + "; timeout is " + timeout); final URLConnection connection = new URL(url).openConnection(); connection.setIfModifiedSince(lastFetchTime); if (timeout != 0) { connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); } final HttpURLConnection http = (HttpURLConnection) connection; if (connection instanceof HttpsURLConnection) { final HttpsURLConnection https = (HttpsURLConnection) connection; https.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(final String arg0, final SSLSession arg1) { return true; } }); } http.setInstanceFollowRedirects(false); http.setRequestMethod(method); http.setAllowUserInteraction(true); for (final String key : requestProps.keySet()) { http.addRequestProperty(key, requestProps.get(key)); } if (method.equals(POST_STR) && data != null) { http.setDoOutput(true); // Triggers POST. try (final OutputStream output = http.getOutputStream()) { output.write(data.getBytes(UTF8_STR)); } } connection.connect(); return http; }
From source file:com.amazonaws.http.UrlHttpClient.java
void configureConnection(HttpRequest request, HttpURLConnection connection) { // configure the connection connection.setConnectTimeout(config.getConnectionTimeout()); connection.setReadTimeout(config.getSocketTimeout()); // disable redirect and cache connection.setInstanceFollowRedirects(false); connection.setUseCaches(false);// w w w . j a va2s. c om // is streaming if (request.isStreaming()) { connection.setChunkedStreamingMode(0); } // configure https connection if (connection instanceof HttpsURLConnection) { final HttpsURLConnection https = (HttpsURLConnection) connection; // disable cert check /* * Commented as per https://support.google.com/faqs/answer/6346016. Uncomment for testing. if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) { disableCertificateValidation(https); } */ if (config.getTrustManager() != null) { enableCustomTrustManager(https); } } }
From source file:org.spigotmc.timings.TimingsExport.java
@Override public void run() { sender.sendMessage(ChatColor.GREEN + "Preparing Timings Report..."); out.put("data", toObjectMapper(history, new Function<TimingHistory, JSONPair>() { @Override//from w w w. j a v a2s.co m public JSONPair apply(TimingHistory input) { return input.export(); } })); String response = null; try { HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection(); con.setDoOutput(true); con.setRequestProperty("User-Agent", "Spigot/" + Bukkit.getServerName() + "/" + InetAddress.getLocalHost().getHostName()); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); OutputStream request = new GZIPOutputStream(con.getOutputStream()) { { this.def.setLevel(7); } }; request.write(JSONValue.toJSONString(out).getBytes("UTF-8")); request.close(); response = getResponse(con); if (con.getResponseCode() != 302) { sender.sendMessage( ChatColor.RED + "Upload Error: " + con.getResponseCode() + ": " + con.getResponseMessage()); sender.sendMessage(ChatColor.RED + "Check your logs for more information"); if (response != null) { Bukkit.getLogger().log(Level.SEVERE, response); } return; } String location = con.getHeaderField("Location"); sender.sendMessage(ChatColor.GREEN + "View Timings Report: " + location); if (!(sender instanceof ConsoleCommandSender)) { Bukkit.getLogger().log(Level.INFO, "View Timings Report: " + location); } if (response != null && !response.isEmpty()) { Bukkit.getLogger().log(Level.INFO, "Timing Response: " + response); } } catch (IOException ex) { sender.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information"); if (response != null) { Bukkit.getLogger().log(Level.SEVERE, response); } Bukkit.getLogger().log(Level.SEVERE, "Could not paste timings", ex); } }
From source file:android.widget.TiVideoView4.java
private void setDataSource() { try {/*from ww w . j a va 2 s. co m*/ if (mUri.getScheme().equals("http") || mUri.getScheme().equals("https")) { // Media player doesn't handle redirects, try to follow them here while (true) { // java.net.URL doesn't handle rtsp if (mUri.getScheme() != null && mUri.getScheme().equals("rtsp")) break; URL url = new URL(mUri.toString()); HttpURLConnection cn = (HttpURLConnection) url.openConnection(); cn.setInstanceFollowRedirects(false); String location = cn.getHeaderField("Location"); if (location != null) { String host = mUri.getHost(); int port = mUri.getPort(); String scheme = mUri.getScheme(); mUri = Uri.parse(location); if (mUri.getScheme() == null) { // Absolute URL on existing host/port/scheme if (scheme == null) { scheme = "http"; } String authority = port == -1 ? host : host + ":" + port; mUri = mUri.buildUpon().scheme(scheme).encodedAuthority(authority).build(); } } else { break; } } } mMediaPlayer.setDataSource(getContext(), mUri); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.nicolacimmino.expensestracker.tracker.expenses_api.ExpensesApiRequest.java
public boolean performRequest() { jsonResponseArray = null;//from ww w.java 2s . c o m jsonResponseObject = null; HttpURLConnection connection = null; try { // Get the request JSON document as U*TF-8 encoded bytes, suitable for HTTP. mRequestData = ((mRequestData != null) ? mRequestData : new JSONObject()); byte[] postDataBytes = mRequestData.toString(0).getBytes("UTF-8"); URL url = new URL(mUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(mRequestMethod == "GET" ? false : true); // No body data for GET connection.setDoInput(true); connection.setInstanceFollowRedirects(true); connection.setRequestMethod(mRequestMethod); connection.setUseCaches(false); // For all methods except GET we need to include data in the body. if (mRequestMethod != "GET") { connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", "" + Integer.toString(postDataBytes.length)); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(postDataBytes); wr.flush(); wr.close(); } if (connection.getResponseCode() == 200) { InputStreamReader in = new InputStreamReader((InputStream) connection.getContent()); BufferedReader buff = new BufferedReader(in); String line = buff.readLine().toString(); buff.close(); Object json = new JSONTokener(line).nextValue(); if (json.getClass() == JSONObject.class) { jsonResponseObject = (JSONObject) json; } else if (json.getClass() == JSONArray.class) { jsonResponseArray = (JSONArray) json; } // else members will be left to null indicating no valid response. return true; } } catch (MalformedURLException e) { Log.e(TAG, e.getMessage()); } catch (IOException e) { Log.e(TAG, e.getMessage()); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } return false; }