List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:jmc.util.UtlFbComents.java
public static void getURLComentarios(String url, Long numComents) throws JMCException { File f = null;/*from ww w . ja v a2 s . c o m*/ try { Properties props = ConfigPropiedades.getProperties("props_config.properties"); CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); URL ur = new URL( "http://graph.facebook.com/comments?id=" + url + "&limit=" + numComents + "&filter=stream"); HttpURLConnection cn = (HttpURLConnection) ur.openConnection(); cn.setRequestProperty("user-agent", props.getProperty("navegador")); cn.setInstanceFollowRedirects(false); cn.setUseCaches(false); cn.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream())); String dirTempHtml = props.getProperty("archive_json") + "/"; File fld = new File(dirTempHtml); boolean creado = fld.exists() ? true : fld.mkdir(); if (creado) { String archFile = "archivo.json"; String archivo = dirTempHtml + archFile; String linea = null; f = new File(archivo); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); while ((linea = br.readLine()) != null) { bw.append(linea); } bw.close(); cn.disconnect(); List<Fbcoment> lfb = Convertidor.getFbcomentObjects(1l, archivo); // Fbcoment.actComents(idContenido, lfb); } else { cn.disconnect(); } } catch (IOException e) { throw new JMCException(e); } }
From source file:jmc.util.UtlFbComents.java
public static void getComentarios(Long idContenido, Long numComents) throws JMCException { File f = null;//from www . j a va 2 s . c om try { Properties props = ConfigPropiedades.getProperties("props_config.properties"); CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); URL ur = new URL("http://graph.facebook.com/comments?id=" + Contenido.getContenido("Where cont_id = '" + idContenido + "'").get(0).getEnlaceURL() + "&limit=" + numComents + "&filter=stream"); HttpURLConnection cn = (HttpURLConnection) ur.openConnection(); cn.setRequestProperty("user-agent", props.getProperty("navegador")); cn.setInstanceFollowRedirects(false); cn.setUseCaches(false); cn.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream())); String dirTempHtml = props.getProperty("archive_json") + "/"; File fld = new File(dirTempHtml); boolean creado = fld.exists() ? true : fld.mkdir(); if (creado) { String archFile = idContenido + ".json"; String archivo = dirTempHtml + archFile; String linea = null; f = new File(archivo); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); while ((linea = br.readLine()) != null) { bw.append(linea); } bw.close(); cn.disconnect(); List<Fbcoment> lfb = Convertidor.getFbcomentObjects(idContenido, archivo); Fbcoment.actComents(idContenido, lfb); } else { cn.disconnect(); } } catch (IOException e) { throw new JMCException(e); } }
From source file:Main.java
/** * Return an {@link InputStream} from the given url or null if failed to retrieve the content * /* w w w . ja v a2s.c o m*/ * @param uri * @return */ static InputStream openRemoteInputStream(Uri uri) { java.net.URL finalUrl; try { finalUrl = new java.net.URL(uri.toString()); } catch (MalformedURLException e) { e.printStackTrace(); return null; } HttpURLConnection connection; try { connection = (HttpURLConnection) finalUrl.openConnection(); } catch (IOException e) { e.printStackTrace(); return null; } connection.setInstanceFollowRedirects(false); int code; try { code = connection.getResponseCode(); } catch (IOException e) { e.printStackTrace(); return null; } // permanent redirection if (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_SEE_OTHER) { String newLocation = connection.getHeaderField("Location"); return openRemoteInputStream(Uri.parse(newLocation)); } try { return (InputStream) finalUrl.getContent(); } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:com.fastbootmobile.encore.api.common.HttpGet.java
/** * Downloads the data from the provided URL. * @param inUrl The URL to get from/*ww w . j ava 2s . c om*/ * @param query The query field. '?' + query will be appended automatically, and the query data * MUST be encoded properly. * @return A byte array of the data */ public static byte[] getBytes(String inUrl, String query, boolean cached) throws IOException, RateLimitException { final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query)); Log.d(TAG, "Formatted URL: " + formattedUrl); URL url = new URL(formattedUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)"); urlConnection.setUseCaches(cached); urlConnection.setInstanceFollowRedirects(true); int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale); try { final int status = urlConnection.getResponseCode(); // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway. if (status == HttpURLConnection.HTTP_OK) { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); int contentLength = urlConnection.getContentLength(); if (contentLength <= 0) { // No length? Let's allocate 100KB. contentLength = 100 * 1024; } ByteArrayBuffer bab = new ByteArrayBuffer(contentLength); BufferedInputStream bis = new BufferedInputStream(in); int character; while ((character = bis.read()) != -1) { bab.append(character); } return bab.toByteArray(); } else if (status == HttpURLConnection.HTTP_NOT_FOUND) { // 404 return new byte[] {}; } else if (status == HttpURLConnection.HTTP_FORBIDDEN) { return new byte[] {}; } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) { throw new RateLimitException(); } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */ || status == HttpURLConnection.HTTP_SEE_OTHER) { // We've been redirected, follow the new URL final String followUrl = urlConnection.getHeaderField("Location"); Log.e(TAG, "Redirected to: " + followUrl); return getBytes(followUrl, "", cached); } else { Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")"); return new byte[] {}; } } finally { urlConnection.disconnect(); } }
From source file:mashapeautoloader.MashapeAutoloader.java
/** * @param libraryName/*from w w w . j av a2s . com*/ * * Returns false if something wrong, otherwise true (API interface * already exists or just well downloaded) */ private static boolean downloadLib(String libraryName) { URL url; URLConnection urlConn; // check (or make) for apiStore directory File apiStoreDir = new File(apiStore); if (!apiStoreDir.isDirectory()) apiStoreDir.mkdir(); String javaFilePath = apiStore + libraryName + ".java"; File javaFile = new File(javaFilePath); // check if the API interface exists if (javaFile.exists()) return true; try { // download the API interface's archive url = new URL(MASHAPE_DOWNLOAD_ROOT + libraryName); urlConn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setInstanceFollowRedirects(false); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setUseCaches(false); // extract the archive stream ZipInputStream zip = new ZipInputStream(urlConn.getInputStream()); String expectedEntryName = libraryName + ".java"; while (true) { ZipEntry nextEntry = zip.getNextEntry(); if (nextEntry == null) return false; String name = nextEntry.getName(); if (name.equals(expectedEntryName)) { // save .java locally FileOutputStream javaFileStream = new FileOutputStream(javaFilePath); byte[] buf = new byte[1024]; int n; while ((n = zip.read(buf, 0, 1024)) > -1) javaFileStream.write(buf, 0, n); // compile it into .class file JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int result = compiler.run(null, null, null, javaFilePath); System.out.println(result); return result == 0; } } } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:qurandwnld.SyncDbHelper.java
public static ServerResponse bringMorag3ahFromServer(String username, String password) throws Exception { String urlParameters = String.format("username=%s&password=%s", URLEncoder.encode(username, "UTF-8"), URLEncoder.encode(password, "UTF-8")); byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; String request = "http://localhost:55622/Server/GetMorag3ahSelections"; URL url = new URL(request); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);//from ww w. j a v a 2 s . c o m conn.setInstanceFollowRedirects(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", Integer.toString(postDataLength)); conn.setUseCaches(false); try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) { wr.write(postData); } Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); StringBuilder json = new StringBuilder(); for (int c = in.read(); c != -1; c = in.read()) json.append((char) c); String str = json.toString(); int idx = str.indexOf(":"); ServerResponse res = new ServerResponse(); res.code = Integer.parseInt(str.substring(0, idx)); res.message = str.substring(idx + 2); if (res.code == 200) { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc; try (ByteArrayInputStream stream = new ByteArrayInputStream( res.message.getBytes(StandardCharsets.UTF_8))) { doc = dBuilder.parse(stream); } res.message = null; doc.getDocumentElement().normalize(); Connection c = DbHelper.CONNECTION; try (Statement s = c.createStatement()) { s.executeUpdate("DELETE FROM DorrahShahed_Others"); NodeList nList = doc.getElementsByTagName("DorrahShahed"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; s.executeUpdate(String.format( "INSERT INTO DorrahShahed_Others (DetailID, BeitID, BeitPart, IsNew, IsDeleted) " + "VALUES (%d, %d, %d, 0, 0)", Integer.parseInt(eElement.getAttribute("DetailID")), Integer.parseInt(eElement.getAttribute("BeitID")), Integer.parseInt(eElement.getAttribute("BeitPart")))); } } s.executeUpdate("DELETE FROM ShatibiyyahShahed_Others"); nList = doc.getElementsByTagName("ShatibiyyahShahed"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; s.executeUpdate(String.format( "INSERT INTO ShatibiyyahShahed_Others (DetailID, BeitID, BeitPart, IsNew, IsDeleted) " + "VALUES (%d, %d, %d, 0, 0)", Integer.parseInt(eElement.getAttribute("DetailID")), Integer.parseInt(eElement.getAttribute("BeitID")), Integer.parseInt(eElement.getAttribute("BeitPart")))); } } } } return res; }
From source file:com.mopaas_mobile.http.BaseHttpRequester.java
public static String doPOST(String urlstr, List<BasicNameValuePair> params) throws IOException { String result = null;// w w w . jav a 2 s .com URL url = new URL(urlstr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // connection.setRequestProperty("token",token); connection.setConnectTimeout(30000); connection.setReadTimeout(30000); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); String content = ""; if (params != null && params.size() > 0) { for (int i = 0; i < params.size(); i++) { content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8") + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8"); } out.writeBytes(content.substring(1)); } out.flush(); out.close(); InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer b = new StringBuffer(); int ch; while ((ch = br.read()) != -1) { b.append((char) ch); } result = b.toString().trim(); connection.disconnect(); return result; }
From source file:pt.ist.maidSyncher.api.activeCollab.JsonRest.java
public static Object processGet(String urlStr) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);// w ww . j av a 2 s .c o m conn.setDoInput(true); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "text/plain"); conn.setRequestProperty("charset", "utf-8"); conn.connect(); InputStream is = conn.getInputStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); LOGGER.trace(jsonText); return JSONValue.parse(jsonText); } finally { is.close(); conn.disconnect(); } }
From source file:Main.java
public static String customrequest(String url, HashMap<String, String> params, String method) { try {/*from ww w . java2 s . c o m*/ URL postUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod(method); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)"); conn.connect(); OutputStream out = conn.getOutputStream(); StringBuilder sb = new StringBuilder(); if (null != params) { int i = params.size(); for (Map.Entry<String, String> entry : params.entrySet()) { if (i == 1) { sb.append(entry.getKey() + "=" + entry.getValue()); } else { sb.append(entry.getKey() + "=" + entry.getValue() + "&"); } i--; } } String content = sb.toString(); out.write(content.getBytes("UTF-8")); out.flush(); out.close(); InputStream inStream = conn.getInputStream(); String result = inputStream2String(inStream); conn.disconnect(); return result; } catch (Exception e) { // TODO: handle exception } return null; }
From source file:chen.android.toolkit.network.HttpConnection.java
/** * </br><b>title : </b> ????POST?? * </br><b>description :</b>????POST?? * </br><b>time :</b> 2012-7-8 ?4:34:08 * @param method ??//w w w . j a v a 2 s .co m * @param url POSTURL * @param datas ???? * @return ??? * @throws IOException */ private static InputStream connect(String method, URL url, byte[]... datas) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(method); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.setConnectTimeout(6 * 1000); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); OutputStream outputStream = conn.getOutputStream(); for (byte[] data : datas) { outputStream.write(data); } outputStream.close(); return conn.getInputStream(); }