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.trafficspaces.api.controller.Connector.java
public String sendRequest(String path, String contentType, String method, String data) throws IOException, TrafficspacesAPIException { URL url = new URL(endPoint.baseURI + path); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true);/*from w w w . j a v a 2 s. c o m*/ httpCon.setRequestMethod(method.toUpperCase()); String basicAuth = "Basic " + Base64.encodeBytes((endPoint.username + ":" + endPoint.password).getBytes()); httpCon.setRequestProperty("Authorization", basicAuth); httpCon.setRequestProperty("Content-Type", contentType + "; charset=UTF-8"); httpCon.setRequestProperty("Accept", contentType); if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) { httpCon.setRequestProperty("Content-Length", String.valueOf(data.length())); OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream()); out.write(data); out.close(); } else { httpCon.connect(); } char[] responseData = null; try { responseData = readResponseData(httpCon.getInputStream(), "UTF-8"); } catch (FileNotFoundException fnfe) { // HTTP 404. Ignore and return null } String responseDataString = null; if (responseData != null) { int responseCode = httpCon.getResponseCode(); String redirectURL = null; if ((responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_CREATED) && (redirectURL = httpCon.getHeaderField("Location")) != null) { //System.out.println("Response code = " +responseCode + ". Redirecting to " + redirectURL); return sendRequest(redirectURL, contentType); } if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) { throw new TrafficspacesAPIException( "HTTP Error: " + responseCode + "; Data: " + new String(responseData)); } //System.out.println("Headers: " + httpCon.getHeaderFields()); //System.out.println("Data: " + new String(responseData)); responseDataString = new String(responseData); } return responseDataString; }
From source file:com.github.dozermapper.core.builder.xml.SchemaLSResourceResolver.java
/** * Attempts to open a http connection for the systemId resource, and follows the first redirect * * @param systemId url to the XSD/*from w w w . j a va 2 s. c om*/ * @return stream to XSD * @throws IOException if fails to find XSD */ private InputStream resolveFromURL(String systemId) throws IOException { LOG.debug("Trying to download [{}]", systemId); URL obj = new URL(systemId); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); int status = conn.getResponseCode(); if ((status != HttpURLConnection.HTTP_OK) && (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)) { LOG.debug("Received status of {}, attempting to follow Location header", status); String newUrl = conn.getHeaderField("Location"); conn = (HttpURLConnection) new URL(newUrl).openConnection(); } return conn.getInputStream(); }
From source file:net.mceoin.cominghome.api.NestUtil.java
private static String getNestAwayStatusCall(String access_token) { String away_status = ""; String urlString = "https://developer-api.nest.com/structures?auth=" + access_token; log.info("url=" + urlString); StringBuilder builder = new StringBuilder(); boolean error = false; String errorResult = ""; HttpURLConnection urlConnection = null; try {/* ww w . ja v a 2s . c o m*/ URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0"); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setConnectTimeout(15000); urlConnection.setReadTimeout(15000); // urlConnection.setChunkedStreamingMode(0); // urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); boolean redirect = false; // normally, 3xx is redirect int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 // Temporary redirect || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } // System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = urlConnection.getHeaderField("Location"); // open the new connnection again urlConnection = (HttpURLConnection) new URL(newUrl).openConnection(); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); // urlConnection.setChunkedStreamingMode(0); // System.out.println("Redirect to URL : " + newUrl); } int statusCode = urlConnection.getResponseCode(); log.info("statusCode=" + statusCode); if ((statusCode == HttpURLConnection.HTTP_OK)) { error = false; InputStream response; response = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); JSONObject structure = object.getJSONObject(key); if (structure.has("away")) { away_status = structure.getString("away"); } else { log.info("missing away"); } } } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad auth error = true; errorResult = "Unauthorized"; } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { error = true; InputStream response; response = urlConnection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("error")) { // error = Internal Error on bad structure_id errorResult = object.getString("error"); log.info("errorResult=" + errorResult); } } } else { error = true; errorResult = Integer.toString(statusCode); } } catch (IOException e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("IOException: " + errorResult); } catch (Exception e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("Exception: " + errorResult); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (error) away_status = "Error: " + errorResult; return away_status; }
From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java
public String responseCaptcha(String responseCaptcha) { String url = "https://ipv4.google.com/sorry/CaptchaRedirect"; String request = url + "?q=" + q + "&hl=es&continue=" + continueCaptcha + "&id=" + idCaptcha + "&captcha=" + responseCaptcha + "&submit=Enviar"; String newCookie = ""; try {//from www.j ava2 s. c o m URL obj = new URL(request); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); // add request header con.setRequestProperty("Host", "ipv4.google.com"); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0"); con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); con.setRequestProperty("Accept-Language", "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3"); con.setRequestProperty("Accept-Encoding", "gzip, deflate, br"); con.setRequestProperty("Cookie", tokenCookie + "; path=/; domain=google.com"); con.addRequestProperty("Connection", "keep-alive"); con.setRequestProperty("Referer", referer); //con.connect(); boolean redirect = false; con.setInstanceFollowRedirects(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) { // get redirect url from "location" header field String newUrl = con.getHeaderField("Location"); // open the new connnection again con = (HttpURLConnection) new URL(newUrl).openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0"); con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); con.setRequestProperty("Referer", referer); con.setRequestProperty("Accept-Encoding", "gzip, deflate"); con.setRequestProperty("Cookie", tokenCookie); con.addRequestProperty("Connection", "keep-alive"); // Find the cookie String nextURL = URLDecoder.decode(newUrl, "UTF-8"); String[] k = nextURL.split("&"); for (String a : k) { if (a.startsWith("google_abuse=")) { String temp = a.replace("google_abuse=", ""); String[] c = temp.split(";"); for (String j : c) { if (j.startsWith("GOOGLE_ABUSE_EXEMPTION")) { newCookie = j; } } } } } con.connect(); if (con.getResponseCode() == 200) { newCookie = tokenCookie; } } catch (IOException e) { e.printStackTrace(); } return newCookie; }
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 w w w . ja v a2 s . co m*/ 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:com.adaptris.http.HttpClientTransport.java
private boolean hasMoved(HttpResponse r) { return (r.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) || (r.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM); }
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
public static String getRedirectUrl(REGION region) { String result = ""; switch (region) { case EU:/*from w w w. ja v a2 s.co 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:mobi.jenkinsci.ci.client.JenkinsClient.java
public AbstractNode execute(final String command) throws IOException { final HttpPost post = new HttpPost(getCommandUrl(command)); try {// w w w. j a v a 2s .c o m final HttpResponse response = http.execute(post); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) { return new ResetNode(); } else { throw new IOException( "Command " + command + " *FAILED* with HTTP Status " + response.getStatusLine()); } } finally { post.releaseConnection(); } }
From source file:vocab.VocabUtils.java
/** * Jena fails to load models in https with content negotiation. Therefore I do * the negotiation here directly// w w w. j av a 2 s .c o m */ 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 {/*from ww w.jav a2 s . c o m*/ 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 ""; }