List of usage examples for java.net URL openConnection
public URLConnection openConnection() throws java.io.IOException
From source file:PostTest.java
/** * Makes a POST request and returns the server response. * @param urlString the URL to post to// w ww. ja va 2s .c o m * @param nameValuePairs a map of name/value pairs to supply in the request. * @return the server reply (either from the input stream or the error stream) */ public static String doPost(String urlString, Map<String, String> nameValuePairs) throws IOException { URL url = new URL(urlString); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); boolean first = true; for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) { if (first) first = false; else out.print('&'); String name = pair.getKey(); String value = pair.getValue(); out.print(name); out.print('='); out.print(URLEncoder.encode(value, "UTF-8")); } out.close(); Scanner in; StringBuilder response = new StringBuilder(); try { in = new Scanner(connection.getInputStream()); } catch (IOException e) { if (!(connection instanceof HttpURLConnection)) throw e; InputStream err = ((HttpURLConnection) connection).getErrorStream(); if (err == null) throw e; in = new Scanner(err); } while (in.hasNextLine()) { response.append(in.nextLine()); response.append("\n"); } in.close(); return response.toString(); }
From source file:com.blogspot.ryanfx.auth.GoogleUtil.java
/** * Sends the auth token to google and gets the json result. * @param token auth token//from w w w . java 2 s. c o m * @return json result if valid request, null if invalid. * @throws IOException * @throws LoginException */ private static String issueTokenGetRequest(String token) throws IOException, LoginException { int timeout = 2000; URL u = new URL("https://www.googleapis.com/oauth2/v2/userinfo"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setRequestProperty("Content-length", "0"); c.setRequestProperty("Authorization", "OAuth " + token); c.setUseCaches(false); c.setAllowUserInteraction(false); c.setConnectTimeout(timeout); c.setReadTimeout(timeout); c.connect(); int status = c.getResponseCode(); if (status == HttpServletResponse.SC_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); return sb.toString(); } else if (status == HttpServletResponse.SC_UNAUTHORIZED) { Logger.getLogger(GoogleUtil.class.getName()).severe("Invalid token request: " + token); } return null; }
From source file:javaphpmysql.JavaPHPMySQL.java
public static void sendGet() { //Creamos un objeto JSON JSONObject jsonObj = new JSONObject(); //Aadimos el nombre, apellidos y email del usuario jsonObj.put("nombre", nombre); jsonObj.put("apellidos", apellidos); jsonObj.put("email", email); //Creamos una lista para almacenar el JSON List l = new LinkedList(); l.addAll(Arrays.asList(jsonObj)); //Generamos el String JSON String jsonString = JSONValue.toJSONString(l); System.out.println("JSON GENERADO:"); System.out.println(jsonString); System.out.println(""); try {//from w w w .java 2s .c o m //Codificar el json a URL jsonString = URLEncoder.encode(jsonString, "UTF-8"); //Generar la URL String url = SERVER_PATH + "listenGet.php?json=" + jsonString; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); //add request header con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
private static void downloadResource(String from, String to) { OutputStream outputStream = null; BufferedInputStream inputStream = null; HttpURLConnection connection = null; URL url; byte[] buffer = new byte[1024]; try {//from w w w . j ava 2 s .c o m url = new URL(from); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); outputStream = new FileOutputStream(to); inputStream = new BufferedInputStream(url.openStream()); int read; while ((read = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, read); } } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) try { outputStream.close(); } catch (IOException e) { } if (inputStream != null) try { inputStream.close(); } catch (IOException e) { } if (connection != null) connection.disconnect(); } }
From source file:Bing.java
/** * * @param query - query to use for the search * @return - a json array of results. each contains a title, description, url, * and some other metadata that can be easily extracted since its in json format *///ww w .ja va2s . c om public static JSONArray search(String query) { try { query = "'" + query + "'"; String encodedQuery = URLEncoder.encode(query, "UTF-8"); System.out.println(encodedQuery); // URL url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=%27car%27"); // URL url = new URL("http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html"); String webPage = "https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=" + encodedQuery + "&$format=JSON"; String name = "6604d12c-3e89-4859-8013-3132f78c1595"; String password = "cefgNRl3OL4PrJJvssxkqLw0VKfYNCgyTe8wNXotUmQ"; String authString = name + ":" + password; System.out.println("auth string: " + authString); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); System.out.println("Base64 encoded auth string: " + authStringEnc); URL url = new URL(webPage); URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine).append("\n"); } in.close(); JSONParser parser = new JSONParser(); JSONArray arr = (JSONArray) ((JSONObject) ((JSONObject) parser.parse(response.toString())).get("d")) .get("results"); JSONObject obj = (JSONObject) arr.get(0); JSONArray out = (JSONArray) obj.get("Web"); return out; // } catch (MalformedURLException ex) { Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.leosys.core.utils.HttpServiceImpl.java
public static String getZiku(String domin) { Properties p = new Properties(); String urls = getXmlPath();// w w w .ja v a 2 s . co m try { p.load(new FileInputStream(urls)); } catch (Exception e) { e.printStackTrace(); } String subUrl = p.getProperty("path"); String restUrl = subUrl + "model=myservice&action=getwebsiteziku&domain=" + domin + "&pagesize=1000"; StringBuffer strBuf; strBuf = new StringBuffer(); try { URL url = new URL(restUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));//? String line = null; while ((line = reader.readLine()) != null) strBuf.append(line + " "); reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(strBuf.toString()); return strBuf.toString(); }
From source file:com.memetix.gun4j.GunshortenAPI.java
protected static JSONObject post(final String serviceUrl, final String paramsString) throws Exception { final URL url = new URL(serviceUrl); final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); if (referrer != null) uc.setRequestProperty("referer", referrer); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING); uc.setRequestProperty("Accept-Charset", ENCODING); uc.setRequestMethod("POST"); uc.setDoOutput(true);/*from www. java 2s.c o m*/ final PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.write(paramsString); pw.close(); uc.getOutputStream().close(); try { final int responseCode = uc.getResponseCode(); final String result = inputStreamToString(uc.getInputStream()); if (responseCode != 200) { throw new Exception("Error from Gunshorten API: " + result); } return parseJSON(result); } finally { uc.getInputStream().close(); if (uc.getErrorStream() != null) { uc.getErrorStream().close(); } } }
From source file:Main.java
public static boolean isConnectionAvailable() { class NetworkCheckTask extends AsyncTask<Void, Void, Boolean> { @Override/* w w w . ja va 2s .co m*/ protected Boolean doInBackground(Void... params) { try { URL url = new URL(MAD_SERVER + "/sync.html"); HttpURLConnection conn = null; conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(999); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); if (conn.getResponseCode() == 200) return true; else return false; } catch (Exception e) { return false; } } } try { NetworkCheckTask async = new NetworkCheckTask(); async.execute(); return async.get(); } catch (Exception e) { return false; } }
From source file:Main.java
@SuppressWarnings("SameParameterValue") public static Bitmap fetchAndRescaleBitmap(String uri, int width, int height) throws IOException { URL url = new URL(uri); BufferedInputStream is = null; try {/* w w w . j av a 2 s. c o m*/ HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); is = new BufferedInputStream(urlConnection.getInputStream()); is.mark(MAX_READ_LIMIT_PER_IMG); int scaleFactor = findScaleFactor(width, height, is); is.reset(); return scaleBitmap(scaleFactor, is); } finally { if (is != null) { is.close(); } } }
From source file:com.gmt2001.HttpRequest.java
public static HttpResponse getData(RequestType type, String url, String post, HashMap<String, String> headers) { Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance()); HttpResponse r = new HttpResponse(); r.type = type;/*ww w . j a v a2 s .c o m*/ r.url = url; r.post = post; r.headers = headers; try { URL u = new URL(url); HttpURLConnection h = (HttpURLConnection) u.openConnection(); for (Entry<String, String> e : headers.entrySet()) { h.addRequestProperty(e.getKey(), e.getValue()); } h.setRequestMethod(type.name()); h.setUseCaches(false); h.setDefaultUseCaches(false); h.setConnectTimeout(timeout); h.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); if (!post.isEmpty()) { h.setDoOutput(true); } h.connect(); if (!post.isEmpty()) { BufferedOutputStream stream = new BufferedOutputStream(h.getOutputStream()); stream.write(post.getBytes()); stream.flush(); stream.close(); } if (h.getResponseCode() < 400) { r.content = IOUtils.toString(new BufferedInputStream(h.getInputStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = true; } else { r.content = IOUtils.toString(new BufferedInputStream(h.getErrorStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = false; } } catch (IOException ex) { r.success = false; r.httpCode = 0; r.exception = ex.getMessage(); com.gmt2001.Console.err.printStackTrace(ex); } return r; }