List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
static String getHttpString(String url) { String result = null;/*from w w w .j a va 2 s.co m*/ // build connection HttpURLConnection huc = getHUC(url); huc.setInstanceFollowRedirects(false); try { // try to establish connection huc.connect(); // get result int responseCode = huc.getResponseCode(); Logd(TAG, "getHttpString response: " + responseCode); // if 200, read http body if (responseCode == 200) { InputStream is = huc.getInputStream(); result = convertStreamToString(is); is.close(); } else { // result = "response code: "+responseCode; } // close connection huc.disconnect(); } catch (Exception e) { Log.e(TAG, "revokeSite FAILED"); e.printStackTrace(); } return result; }
From source file:Main.java
@TargetApi(Build.VERSION_CODES.KITKAT) public static String net(String strUrl, Map<String, Object> params, String method) throws Exception { HttpURLConnection conn = null; BufferedReader reader = null; String rs = null;/*from www . ja v a 2s . c om*/ try { StringBuffer sb = new StringBuffer(); if (method == null || method.equals("GET")) { strUrl = strUrl + "?" + urlencode(params); } URL url = new URL(strUrl); conn = (HttpURLConnection) url.openConnection(); if (method == null || method.equals("GET")) { conn.setRequestMethod("GET"); } else { conn.setRequestMethod("POST"); conn.setDoOutput(true); } conn.setRequestProperty("User-agent", userAgent); conn.setUseCaches(false); conn.setConnectTimeout(DEF_CONN_TIMEOUT); conn.setReadTimeout(DEF_READ_TIMEOUT); conn.setInstanceFollowRedirects(false); conn.connect(); if (params != null && method.equals("POST")) { try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) { out.writeBytes(urlencode(params)); } } InputStream is = conn.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET)); String strRead = null; while ((strRead = reader.readLine()) != null) { sb.append(strRead); } rs = sb.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } } return rs; }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Connects to the server, authenticates the provided username and * password.//from www.j a v a 2 s . co m * * @param username The user's username * @param password The user's password * @return String The authentication token returned by the server (or null) */ public static String authenticate(String username, String accessKey, String base_url) { String token = null; String hash = null; authenticate_log_text = "authenticate()\n"; AUTH_URI = base_url + "/webservice.php"; authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username=" + username + "\n"; Log.d(TAG, "AUTH_URI : "); Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); // =========== get challenge token ============================== ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); try { URL url; // HTTP GET REQUEST url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setUseCaches(false); // for some site that redirects based on user agent con.setInstanceFollowRedirects(true); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15"); con.setAllowUserInteraction(false); int timeout = 20000; con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n"; switch (status) { case 200: case 201: case 302: BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d(TAG, "message body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "body : " + sb.toString(); if (status == 302) { authenticate_log_text = sb.toString(); return null; } JSONObject result = new JSONObject(sb.toString()); Log.d(TAG, result.getString("result")); JSONObject data = new JSONObject(result.getString("result")); token = data.getString("token"); break; case 401: Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "Server auth error"; return null; default: Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "connection status code :" + status; return null; } } catch (ClientProtocolException e) { Log.i(TAG, "getchallenge:http protocol error"); Log.e(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n"; return null; } catch (IOException e) { Log.e(TAG, "getchallenge: IO Exception"); Log.e(TAG, e.getMessage()); Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n"; return null; } catch (JSONException e) { Log.i(TAG, "json exception"); authenticate_log_text = authenticate_log_text + "JSon exception\n"; // TODO Auto-generated catch block e.printStackTrace(); return null; } // ================= login ================== try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(token.getBytes()); m.update(accessKey.getBytes()); hash = new BigInteger(1, m.digest()).toString(16); Log.i(TAG, "hash"); Log.i(TAG, hash); } catch (NoSuchAlgorithmException e) { authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n"; e.printStackTrace(); } try { String charset; charset = "utf-8"; String query = String.format("operation=login&username=%s&accessKey=%s", URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset)); authenticate_log_text = authenticate_log_text + "login()\n"; URLConnection connection = new URL(AUTH_URI).openConnection(); connection.setDoOutput(true); // Triggers POST. int timeout = 20000; connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); connection.setUseCaches(false); OutputStream output = connection.getOutputStream(); try { output.write(query.getBytes(charset)); } finally { try { output.close(); } catch (IOException logOrIgnore) { } } Log.d(TAG, "Query written"); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d(TAG, "message post body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n"; JSONObject result = new JSONObject(sb.toString()); String success = result.getString("success"); Log.i(TAG, success); if (success == "true") { Log.i(TAG, result.getString("result")); Log.i(TAG, "sucesssfully logged in is"); JSONObject data = new JSONObject(result.getString("result")); sessionName = data.getString("sessionName"); Log.i(TAG, sessionName); authenticate_log_text = authenticate_log_text + "successfully logged in\n"; return token; } else { // success is false, retrieve error JSONObject data = new JSONObject(result.getString("error")); authenticate_log_text = "can not login :\n" + data.toString(); return null; } //token = data.getString("token"); //Log.i(TAG,token); } catch (ClientProtocolException e) { Log.d(TAG, "login: http protocol error"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (IOException e) { Log.d(TAG, "login: IO Exception"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "login: IO Exception \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (JSONException e) { Log.d(TAG, "JSON exception"); // TODO Auto-generated catch block authenticate_log_text = authenticate_log_text + "JSON exception "; authenticate_log_text = authenticate_log_text + e.getMessage(); e.printStackTrace(); } return null; // ======================================================================== }
From source file:util.io.IOUtilities.java
/** * Originally copied from javax.swing.JEditorPane. * <p>/*from w w w. j av a2 s . com*/ * Fetches a stream for the given URL, which is about to * be loaded by the <code>setPage</code> method. By * default, this simply opens the URL and returns the * stream. This can be reimplemented to do useful things * like fetch the stream from a cache, monitor the progress * of the stream, etc. * <p> * This method is expected to have the the side effect of * establishing the content type, and therefore setting the * appropriate <code>EditorKit</code> to use for loading the stream. * <p> * If this the stream was an http connection, redirects * will be followed and the resulting URL will be set as * the <code>Document.StreamDescriptionProperty</code> so that relative * URL's can be properly resolved. * * @param page the URL of the page * @param followRedirects Follow redirects. * @param timeout The read timeout. * @param userName The user name to use for the connection. * @param userPassword The password to use for the connection. * @throws IOException if something went wrong. * @return a stream reading data from the specified URL. */ public static InputStream getStream(URL page, boolean followRedirects, int timeout, String userName, String userPassword) throws IOException { URLConnection conn = page.openConnection(); if (userName != null && userPassword != null) { String password = userName + ":" + userPassword; String encodedPassword = new String(Base64.encodeBase64(password.getBytes())); conn.setRequestProperty("Authorization", "Basic " + encodedPassword); } if (timeout > 0) { conn.setReadTimeout(timeout); } if (followRedirects && (conn instanceof HttpURLConnection)) { HttpURLConnection hconn = (HttpURLConnection) conn; hconn.setInstanceFollowRedirects(false); int response = hconn.getResponseCode(); boolean redirect = (response >= 300 && response <= 399); // In the case of a redirect, we want to actually change the URL // that was input to the new, redirected URL if (redirect) { String loc = conn.getHeaderField("Location"); if (loc == null) { throw new FileNotFoundException( "URL points to a redirect without " + "target location: " + page); } if (loc.startsWith("http")) { page = new URL(loc); } else { page = new URL(page, loc); } return getStream(page, followRedirects, timeout, userName, userPassword); } } InputStream in = conn.getInputStream(); return in; }
From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
static String getUserInfo(String server_url, String access_token) { // android.os.Debug.waitForDebugger(); Log.d(TAG, "getUserInfo server_url=" + server_url); Log.d(TAG, "getUserInfo access_token=" + access_token); // check if server is valid if (isEmpty(server_url) || isEmpty(access_token)) { return null; }/*from ww w . ja v a 2s . c om*/ String userinfo_endpoint = getEndpointFromConfigOidc("userinfo_endpoint", server_url); if (isEmpty(userinfo_endpoint)) { Logd(TAG, "getUserInfo : could not get endpoint on server : " + server_url); return null; } Logd(TAG, "getUserInfo : " + userinfo_endpoint); // build connection HttpURLConnection huc = getHUC(userinfo_endpoint + "?access_token=" + access_token); huc.setInstanceFollowRedirects(false); // huc.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); huc.setRequestProperty("Authorization", "Bearer " + access_token); // default result String result = null; try { // try to establish connection huc.connect(); // get result int responseCode = huc.getResponseCode(); Logd(TAG, "getUserInfo 2 response: " + responseCode); // if 200, read http body if (responseCode == 200) { InputStream is = huc.getInputStream(); result = convertStreamToString(is); is.close(); } // close connection huc.disconnect(); } catch (Exception e) { Logd(TAG, "getUserInfo failed"); e.printStackTrace(); } return result; }
From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
public static boolean logout(String server_url) { if (isEmpty(server_url)) { Logd(TAG, "revokSite no server url"); return false; }/*from ww w . j av a 2s .c o m*/ 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); // TAZTAG test // huc.setInstanceFollowRedirects(false); huc.setInstanceFollowRedirects(true); // result : follows redirection is ok for taztag 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:piuk.blockchain.android.util.WalletUtils.java
public static String getURL(String URL) throws Exception { URL url = new URL(URL); String error = null;/* w w w . j a v a2 s . co m*/ for (int ii = 0; ii < DefaultRequestRetry; ++ii) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { connection.setRequestMethod("GET"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); connection.setConnectTimeout(DefaultRequestTimeout); connection.setReadTimeout(DefaultRequestTimeout); connection.setInstanceFollowRedirects(false); connection.connect(); if (connection.getResponseCode() == 200) return IOUtils.toString(connection.getInputStream(), "UTF-8"); else error = IOUtils.toString(connection.getErrorStream(), "UTF-8"); Thread.sleep(5000); } finally { connection.disconnect(); } } return error; }
From source file:org.brickred.socialauth.util.HttpUtil.java
/** * Makes HTTP request using java.net.HTTPURLConnection * /*from w ww .ja v a 2 s . c om*/ * @param urlStr * the URL String * @param requestMethod * Method type * @param body * Body to pass in request. * @param header * Header parameters * @return Response Object * @throws SocialAuthException */ public static Response doHttpRequest(final String urlStr, final String requestMethod, final String body, final Map<String, String> header) throws SocialAuthException { HttpURLConnection conn; try { URL url = new URL(urlStr); if (proxyObj != null) { conn = (HttpURLConnection) url.openConnection(proxyObj); } else { conn = (HttpURLConnection) url.openConnection(); } if (MethodType.POST.toString().equalsIgnoreCase(requestMethod) || MethodType.PUT.toString().equalsIgnoreCase(requestMethod)) { conn.setDoOutput(true); } conn.setDoInput(true); conn.setInstanceFollowRedirects(true); if (timeoutValue > 0) { LOG.debug("Setting connection timeout : " + timeoutValue); conn.setConnectTimeout(timeoutValue); } if (requestMethod != null) { conn.setRequestMethod(requestMethod); } if (header != null) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } // If use POST or PUT must use this OutputStream os = null; if (body != null) { if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod) && !MethodType.DELETE.toString().equals(requestMethod)) { os = conn.getOutputStream(); DataOutputStream out = new DataOutputStream(os); out.write(body.getBytes("UTF-8")); out.flush(); } } conn.connect(); } catch (Exception e) { throw new SocialAuthException(e); } return new Response(conn); }
From source file:org.brickred.socialauth.util.HttpUtil.java
/** * /* w w w.j a va 2 s . c om*/ * @param urlStr * the URL String * @param requestMethod * Method type * @param params * Parameters to pass in request * @param header * Header parameters * @param inputStream * Input stream of image * @param fileName * Image file name * @param fileParamName * Image Filename parameter. It requires in some provider. * @return Response object * @throws SocialAuthException */ public static Response doHttpRequest(final String urlStr, final String requestMethod, final Map<String, String> params, final Map<String, String> header, final InputStream inputStream, final String fileName, final String fileParamName) throws SocialAuthException { HttpURLConnection conn; try { URL url = new URL(urlStr); if (proxyObj != null) { conn = (HttpURLConnection) url.openConnection(proxyObj); } else { conn = (HttpURLConnection) url.openConnection(); } if (requestMethod.equalsIgnoreCase(MethodType.POST.toString()) || requestMethod.equalsIgnoreCase(MethodType.PUT.toString())) { conn.setDoOutput(true); } conn.setDoInput(true); conn.setInstanceFollowRedirects(true); if (timeoutValue > 0) { LOG.debug("Setting connection timeout : " + timeoutValue); conn.setConnectTimeout(timeoutValue); } if (requestMethod != null) { conn.setRequestMethod(requestMethod); } if (header != null) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } // If use POST or PUT must use this OutputStream os = null; if (inputStream != null) { if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod) && !MethodType.DELETE.toString().equals(requestMethod)) { LOG.debug(requestMethod + " request"); String boundary = "----Socialauth-posting" + System.currentTimeMillis(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); boundary = "--" + boundary; os = conn.getOutputStream(); DataOutputStream out = new DataOutputStream(os); write(out, boundary + "\r\n"); if (fileParamName != null) { write(out, "Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\"" + fileName + "\"\r\n"); } else { write(out, "Content-Disposition: form-data; filename=\"" + fileName + "\"\r\n"); } write(out, "Content-Type: " + "multipart/form-data" + "\r\n\r\n"); int b; while ((b = inputStream.read()) != -1) { out.write(b); } // out.write(imageFile); write(out, "\r\n"); Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); write(out, boundary + "\r\n"); write(out, "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); // write(out, // "Content-Type: text/plain;charset=UTF-8 \r\n\r\n"); LOG.debug(entry.getValue()); out.write(entry.getValue().getBytes("UTF-8")); write(out, "\r\n"); } write(out, boundary + "--\r\n"); write(out, "\r\n"); } } conn.connect(); } catch (Exception e) { throw new SocialAuthException(e); } return new Response(conn); }
From source file:com.playhaven.android.req.UrlRequest.java
@Override public String call() throws MalformedURLException, IOException, PlayHavenException { HttpURLConnection connection = (HttpURLConnection) new URL(mInitialUrl).openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestProperty(CoreProtocolPNames.USER_AGENT, UserAgent.USER_AGENT); connection.getContent(); // .getHeaderFields() will return null if headers not accessed once before if (connection.getHeaderFields().containsKey(LOCATION_HEADER)) { return connection.getHeaderField(LOCATION_HEADER); } else {//from www .j a v a2 s . c om throw new PlayHavenException(); } }