List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:tree.love.providers.downloads.DownloadThread.java
/** * Fully execute a single download request. Setup and send the request, * handle the response, and transfer the data to the destination file. *//* ww w . j ava2 s . com*/ private void executeDownload(State state) throws StopRequestException { state.resetBeforeExecute(); setupDestinationFile(state); // skip when already finished; remove after fixing race in 5217390 if (state.mCurrentBytes == state.mTotalBytes) { Log.i(Constants.TAG, "Skipping initiating request for download " + mInfo.mId + "; already completed"); return; } while (state.mRedirectionCount++ < Constants.MAX_REDIRECTS) { // Open connection and follow any redirects until we have a useful // response with body. HttpURLConnection conn = null; try { checkConnectivity(); conn = (HttpURLConnection) state.mUrl.openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(DEFAULT_TIMEOUT); conn.setReadTimeout(DEFAULT_TIMEOUT); addRequestHeaders(state, conn); final int responseCode = conn.getResponseCode(); switch (responseCode) { case HTTP_OK: if (state.mContinuingDownload) { throw new StopRequestException(STATUS_CANNOT_RESUME, "Expected partial, but received OK"); } processResponseHeaders(state, conn); transferData(state, conn); return; case HTTP_PARTIAL: if (!state.mContinuingDownload) { throw new StopRequestException(STATUS_CANNOT_RESUME, "Expected OK, but received partial"); } transferData(state, conn); return; case HTTP_MOVED_PERM: case HTTP_MOVED_TEMP: case HTTP_SEE_OTHER: case HTTP_TEMP_REDIRECT: final String location = conn.getHeaderField("Location"); state.mUrl = new URL(state.mUrl, location); if (responseCode == HTTP_MOVED_PERM) { // Push updated URL back to database state.mRequestUri = state.mUrl.toString(); } continue; case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE: throw new StopRequestException(STATUS_CANNOT_RESUME, "Requested range not satisfiable"); case HTTP_UNAVAILABLE: parseRetryAfterHeaders(state, conn); throw new StopRequestException(HTTP_UNAVAILABLE, conn.getResponseMessage()); case HTTP_INTERNAL_ERROR: throw new StopRequestException(HTTP_INTERNAL_ERROR, conn.getResponseMessage()); default: StopRequestException.throwUnhandledHttpError(responseCode, conn.getResponseMessage()); } } catch (IOException e) { // Trouble with low-level sockets throw new StopRequestException(STATUS_HTTP_DATA_ERROR, e); } finally { if (conn != null) conn.disconnect(); } } throw new StopRequestException(STATUS_TOO_MANY_REDIRECTS, "Too many redirects"); }
From source file:export.GarminUploader.java
private Status connectNew() throws MalformedURLException, IOException, JSONException { Status s = Status.NEED_AUTH;//from w w w . j a va 2 s. c o m s.authMethod = Uploader.AuthMethod.USER_PASS; FormValues fv = new FormValues(); fv.put("service", "http://connect.garmin.com/post-auth/login"); fv.put("clientId", "GarminConnect"); fv.put("consumeServiceTicket", "false"); HttpURLConnection conn = get("https://sso.garmin.com/sso/login", fv); addCookies(conn); expectResponse(conn, 200, "Connection 1: "); getCookies(conn); getFormValues(conn); conn.disconnect(); // try again FormValues data = new FormValues(); data.put("username", username); data.put("password", password); data.put("_eventId", "submit"); data.put("embed", "true"); data.put("lt", formValues.get("lt")); conn = post("https://sso.garmin.com/sso/login", fv); conn.setInstanceFollowRedirects(false); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); postData(conn, data); expectResponse(conn, 200, "Connection 2: "); getCookies(conn); String html = getFormValues(conn); conn.disconnect(); /* this is really horrible */ int start = html.indexOf("?ticket="); if (start == -1) { throw new IOException("Invalid login, unable to locate ticket"); } start += "?ticket=".length(); int end = html.indexOf("'", start); String ticket = html.substring(start, end); // connection 3... fv.clear(); fv.put("ticket", ticket); conn = get("http://connect.garmin.com/post-auth/login", fv); conn.setInstanceFollowRedirects(false); addCookies(conn); expectResponse(conn, 302, "Connection 3: "); List<String> fields = conn.getHeaderFields().get("location"); getCookies(conn); // connection 4... conn = get(fields.get(0), null); conn.setInstanceFollowRedirects(false); addCookies(conn); expectResponse(conn, 302, "Connection 4: "); getCookies(conn); conn.disconnect(); return checkLogin(); }
From source file:org.runnerup.export.GarminUploader.java
private Status connectNew() throws MalformedURLException, IOException, JSONException { Status s = Status.NEED_AUTH;/*from w w w.j a v a 2 s .com*/ s.authMethod = Uploader.AuthMethod.USER_PASS; FormValues fv = new FormValues(); fv.put("service", "https://connect.garmin.com/post-auth/login"); fv.put("clientId", "GarminConnect"); fv.put("consumeServiceTicket", "false"); HttpURLConnection conn = get("https://sso.garmin.com/sso/login", fv); addCookies(conn); expectResponse(conn, 200, "Connection 1: "); getCookies(conn); getFormValues(conn); conn.disconnect(); // try again FormValues data = new FormValues(); data.put("username", username); data.put("password", password); data.put("_eventId", "submit"); data.put("embed", "true"); data.put("lt", formValues.get("lt")); conn = post("https://sso.garmin.com/sso/login", fv); conn.setInstanceFollowRedirects(false); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); postData(conn, data); expectResponse(conn, 200, "Connection 2: "); getCookies(conn); String html = getFormValues(conn); conn.disconnect(); /* this is really horrible */ int start = html.indexOf("?ticket="); if (start == -1) { throw new IOException("Invalid login, unable to locate ticket"); } start += "?ticket=".length(); int end = html.indexOf("'", start); String ticket = html.substring(start, end); System.err.println("ticket: " + ticket); // connection 3... fv.clear(); fv.put("ticket", ticket); conn = get("https://connect.garmin.com/post-auth/login", fv); conn.setInstanceFollowRedirects(false); addCookies(conn); for (int i = 0;; i++) { int code = conn.getResponseCode(); System.err.println("attempt: " + i + " => code: " + code); getCookies(conn); if (code == 200) break; if (code != 302) break; List<String> fields = conn.getHeaderFields().get("location"); conn.disconnect(); conn = get(fields.get(0), null); conn.setInstanceFollowRedirects(false); addCookies(conn); } conn.disconnect(); return Status.OK; // return checkLogin(); }
From source file:de.bps.course.nodes.vc.provider.wimba.WimbaClassroomProvider.java
private String sendRequest(Map<String, String> parameters) { URL url = createRequestUrl(parameters); HttpURLConnection urlConn; try {/*ww w . j a v a 2s. co m*/ urlConn = (HttpURLConnection) url.openConnection(); // setup url connection urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setInstanceFollowRedirects(false); // add content type urlConn.setRequestProperty("Content-Type", CONTENT_TYPE); // add cookie information if (cookie != null) urlConn.setRequestProperty("Cookie", cookie); // send request urlConn.connect(); // detect redirect int code = urlConn.getResponseCode(); boolean moved = code == HttpURLConnection.HTTP_MOVED_PERM | code == HttpURLConnection.HTTP_MOVED_TEMP; if (moved) { String location = urlConn.getHeaderField("Location"); List<String> headerVals = urlConn.getHeaderFields().get("Set-Cookie"); for (String val : headerVals) { if (val.startsWith(COOKIE)) cookie = val; } url = createRedirectUrl(location); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("Cookie", cookie); } // read response BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = input.readLine()) != null) response.append(line).append("\n"); input.close(); if (isLogDebugEnabled()) logDebug("Response: " + response); return response.toString(); } catch (IOException e) { logError("Sending request to Wimba Classroom failed. Request: " + url.toString(), e); return ""; } }
From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java
public boolean logout(String server_url) { if (isEmpty(server_url)) { Logd(TAG, "revokSite no server url"); return false; }//w w w. j a va2 s .c om if (!server_url.endsWith("/")) server_url += "/"; // get end session endpoint String end_session_endpoint = getEndpointFromConfigOidc("end_session_endpoint", server_url); if (isEmpty(end_session_endpoint)) { Logd(TAG, "logout : could not get end_session_endpoint on server : " + server_url); return false; } // set up connection HttpURLConnection huc = getHUC(end_session_endpoint); huc.setInstanceFollowRedirects(false); huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); huc.setDoOutput(true); huc.setChunkedStreamingMode(0); // prepare parameters List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); try { // write parameters to http connection OutputStream os = huc.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); // get URL encoded string from list of key value pairs String postParam = getQuery(nameValuePairs); Logd("Logout", "url: " + end_session_endpoint); Logd("Logout", "POST: " + postParam); writer.write(postParam); writer.flush(); writer.close(); os.close(); // try to connect huc.connect(); // connexion status int responseCode = huc.getResponseCode(); Logd(TAG, "Logout response: " + responseCode); // if 200 - OK if (responseCode == 200) { return true; } huc.disconnect(); } catch (Exception e) { e.printStackTrace(); return false; } return false; }
From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java
String refreshToken(String refresh_token) { // android.os.Debug.waitForDebugger(); // check initialization if (mOcp == null || isEmpty(mOcp.m_server_url)) return null; // nothing to do if (isEmpty(refresh_token)) return null; String postUrl = mOcp.m_server_url + "token"; // set up connection HttpURLConnection huc = getHUC(postUrl); huc.setDoOutput(true);/*from w ww . ja v a2 s.co m*/ huc.setInstanceFollowRedirects(false); huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // prepare parameters List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7); nameValuePairs.add(new BasicNameValuePair("client_id", mOcp.m_client_id)); nameValuePairs.add(new BasicNameValuePair("client_secret", mOcp.m_client_secret)); nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token")); nameValuePairs.add(new BasicNameValuePair("refresh_token", refresh_token)); if (!isEmpty(mOcp.m_scope)) nameValuePairs.add(new BasicNameValuePair("scope", mOcp.m_scope)); try { // write parameters to http connection OutputStream os = huc.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); // get URL encoded string from list of key value pairs String postParam = getQuery(nameValuePairs); Logd("refreshToken", "url: " + postUrl); Logd("refreshToken", "POST: " + postParam); writer.write(postParam); writer.flush(); writer.close(); os.close(); // try to connect huc.connect(); // connexion status int responseCode = huc.getResponseCode(); Logd(TAG, "refreshToken response: " + responseCode); // if 200 - OK, read the json string if (responseCode == 200) { sysout("refresh_token - code " + responseCode); InputStream is = huc.getInputStream(); String result = convertStreamToString(is); is.close(); huc.disconnect(); Logd("refreshToken", "result: " + result); sysout("refresh_token - content: " + result); return result; } huc.disconnect(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.apache.clerezza.integrationtest.web.performance.GetRdf.java
private void post(String postRequestUri) { HttpURLConnection con = null; try {/* w w w . j a va 2 s.c o m*/ rdfResource = "<rdf:RDF\n" + " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" + " xmlns:j.0=\"http://discobits.org/ontology#\" > \n" + " <rdf:Description rdf:about=\"" + resourceUri + "\">\n" + " <rdf:type rdf:resource=\"http://discobits.org/ontology#XHTMLInfoDiscoBit\"/>\n" + " <j.0:infoBit rdf:parseType=\"Literal\">some <em xmlns=\"http://www.w3.org/1999/xhtml\">xhtml</em> content</j.0:infoBit>\n" + " </rdf:Description>\n" + "</rdf:RDF>\n"; URL url = new URL(postRequestUri); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept", "*/*"); con.setRequestProperty("Content-Type", "application/rdf+xml"); con.setRequestProperty("Authorization", "Basic " + authString); con.setInstanceFollowRedirects(false); con.setDoOutput(true); OutputStream outputStream = con.getOutputStream(); outputStream.write(rdfResource.getBytes("UTF-8")); outputStream.close(); int responseCode = con.getResponseCode(); if (responseCode >= 400) { throw new RuntimeException("GetRdf: (POST) unexpected " + "response code: " + responseCode); } } catch (MalformedURLException me) { throw new RuntimeException(me); } catch (IOException ioe) { throw new RuntimeException(ioe); } finally { con.disconnect(); } }
From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java
public String doRedirect(String urlRedirect, boolean useTim) { // android.os.Debug.waitForDebugger(); try {/* w w w . ja va 2s . com*/ // with server phpOIDC, check for '#' if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?")) || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) { String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&"); String code = ""; String state = ""; String state_key = "state"; for (int i = 0; i < params.length; i++) { String param = params[i]; int idxEqual = param.indexOf('='); if (idxEqual >= 0) { String key = param.substring(0, idxEqual); String value = param.substring(idxEqual + 1); if (key.startsWith("code")) code = value; if (key.startsWith("state")) state = value; if (key.startsWith("session_state")) { state = value; state_key = "session_state"; } } } // display code and state Logd(TAG, "doRedirect => code: " + code + " / state: " + state); // doRepost(code,state); if (code.length() > 0) { // get token_endpoint endpoint String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url); if (isEmpty(token_endpoint)) { Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url); return null; } List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); HttpURLConnection huc = getHUC(token_endpoint); huc.setInstanceFollowRedirects(false); if (useTim) { if (mUsePrivateKeyJWT) { nameValuePairs.add(new BasicNameValuePair("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")); String client_assertion = secureStorage.getPrivateKeyJwt(token_endpoint); Logd(TAG, "client_assertion: " + client_assertion); nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion)); } else { huc.setRequestProperty("Authorization", "Basic " + secureStorage.getClientSecretBasic()); } } else { String authorization = (mOcp.m_client_id + ":" + mOcp.m_client_secret); authorization = Base64.encodeToString(authorization.getBytes(), Base64.DEFAULT); huc.setRequestProperty("Authorization", "Basic " + authorization); } huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); huc.setDoOutput(true); huc.setChunkedStreamingMode(0); OutputStream os = huc.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8"); BufferedWriter writer = new BufferedWriter(out); nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code")); nameValuePairs.add(new BasicNameValuePair("code", code)); nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri)); if (state != null && state.length() > 0) nameValuePairs.add(new BasicNameValuePair(state_key, state)); // write URL encoded string from list of key value pairs writer.write(getQuery(nameValuePairs)); writer.flush(); writer.close(); out.close(); os.close(); Logd(TAG, "doRedirect => before connect"); huc.connect(); int responseCode = huc.getResponseCode(); System.out.println("2 - code " + responseCode); Log.d(TAG, "doRedirect => responseCode " + responseCode); InputStream in = null; try { in = new BufferedInputStream(huc.getInputStream()); } catch (IOException ioe) { sysout("io exception: " + huc.getErrorStream()); } if (in != null) { String result = convertStreamToString(in); // now you have the string representation of the HTML request in.close(); Logd(TAG, "doRedirect: " + result); // save as static for now return result; } else { Logd(TAG, "doRedirect null"); } } } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.runnerup.export.GarminSynchronizer.java
private Status connectNew() throws MalformedURLException, IOException, JSONException { Status s = Status.NEED_AUTH;//from w w w .j av a 2 s. c om s.authMethod = Synchronizer.AuthMethod.USER_PASS; FormValues fv = new FormValues(); fv.put("service", "https://connect.garmin.com/post-auth/login"); fv.put("clientId", "GarminConnect"); fv.put("consumeServiceTicket", "false"); HttpURLConnection conn = get("https://sso.garmin.com/sso/login", fv); addCookies(conn); expectResponse(conn, 200, "Connection 1: "); getCookies(conn); getFormValues(conn); conn.disconnect(); // try again FormValues data = new FormValues(); data.put("username", username); data.put("password", password); data.put("_eventId", "submit"); data.put("embed", "true"); data.put("lt", formValues.get("lt")); conn = post("https://sso.garmin.com/sso/login", fv); conn.setInstanceFollowRedirects(false); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); SyncHelper.postData(conn, data); expectResponse(conn, 200, "Connection 2: "); getCookies(conn); String html = getFormValues(conn); conn.disconnect(); /* this is really horrible */ int start = html.indexOf("?ticket="); if (start == -1) { throw new IOException("Invalid login, unable to locate ticket"); } start += "?ticket=".length(); int end = html.indexOf("'", start); String ticket = html.substring(start, end); Log.e(getName(), "ticket: " + ticket); // connection 3... fv.clear(); fv.put("ticket", ticket); conn = get("https://connect.garmin.com/post-auth/login", fv); conn.setInstanceFollowRedirects(false); addCookies(conn); for (int i = 0;; i++) { int code = conn.getResponseCode(); Log.e(getName(), "attempt: " + i + " => code: " + code); getCookies(conn); if (code == HttpStatus.SC_OK) break; if (code != HttpStatus.SC_MOVED_TEMPORARILY) break; List<String> fields = conn.getHeaderFields().get("location"); conn.disconnect(); conn = get(fields.get(0), null); conn.setInstanceFollowRedirects(false); addCookies(conn); } conn.disconnect(); return Status.OK; // return checkLogin(); }
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 ww w . j a 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; }