List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:com.gliffy.restunit.http.JavaHttp.java
/** Performs an HTTP GET. * @param request the request describing the GET. * @return a response//w ww .j a v a2 s. c o m * @throws IOException if HttpURLConnection generated an IO Exception */ public HttpResponse get(HttpRequest request) throws IOException { HttpURLConnection connection = getConnection(request); connection.setRequestMethod("GET"); connection.connect(); HttpResponse response = createResponse(connection); connection.disconnect(); return response; }
From source file:com.gliffy.restunit.http.JavaHttp.java
/** Performs an HTTP HEAD. * @param request the request describing the HEAD. * @return a response/*ww w . j a va 2s . c o m*/ * @throws IOException if HttpURLConnection generated an IO Exception */ public HttpResponse head(HttpRequest request) throws IOException { HttpURLConnection connection = getConnection(request); connection.setRequestMethod("HEAD"); connection.connect(); HttpResponse response = createResponse(connection); connection.disconnect(); return response; }
From source file:piuk.MyRemoteWallet.java
private static String fetchURL(String URL) throws Exception { if (URL.indexOf("?") > 0) { URL += "&api_code=" + getApiCode(); } else {//from w w w. j a va 2 s .c o m URL += "?api_code=" + getApiCode(); } URL url = new URL(URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestMethod("GET"); connection.setConnectTimeout(180000); connection.setReadTimeout(180000); connection.setInstanceFollowRedirects(false); connection.connect(); if (connection.getResponseCode() == 200) return IOUtils.toString(connection.getInputStream(), "UTF-8"); else if (connection.getResponseCode() == 500) throw new Exception("Error From Server: " + IOUtils.toString(connection.getErrorStream(), "UTF-8")); else throw new Exception("Unknown response from server (" + connection.getResponseCode() + ") " + IOUtils.toString(connection.getErrorStream(), "UTF-8")); } finally { connection.disconnect(); } }
From source file:com.gliffy.restunit.http.JavaHttp.java
/** Performs an HTTP DELETE. * @param request the request describing the DELETE. * @return a response//from w w w .jav a 2 s . co m * @throws IOException if HttpURLConnection generated an IO Exception */ public HttpResponse delete(HttpRequest request) throws IOException { HttpURLConnection connection = getConnection(request); connection.setRequestMethod("DELETE"); connection.connect(); HttpResponse response = createResponse(connection); connection.disconnect(); return response; }
From source file:weatherRoute.MapHandler.java
public void testing() { //replace these with input values String origin = "Boise"; String destination = "Rexburg"; String apiQuery = "https://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&key=AIzaSyDbWBUUbN6UHlG9auqFVGmN6WJY9HSe8YI"; try {//from w w w . jav a 2 s. c o m URL url = new URL(apiQuery); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); JsonParser jp = new JsonParser(); JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //You have to step through the ugly, JSON within array within JSON stuff. JsonArray stepsArray = root.getAsJsonObject().getAsJsonArray("routes").get(0).getAsJsonObject() .getAsJsonArray("legs").get(0).getAsJsonObject().getAsJsonArray("steps"); //loop through steps to get city locations for (JsonElement element : stepsArray) { //this gets a string value of the distance in miles String distance = element.getAsJsonObject().get("distance").getAsJsonObject().get("text") .toString(); //parse return value and cast to a Double to be able to compare distance = distance.replace(" mi", ""); distance = distance.replace("\"", ""); Double test = Double.parseDouble(distance); //this limits out all the short .5 mile steps //should mostly get different cities now if (Double.compare(test, 10.0) > 0) { System.out.println("TEST DISTANCE: " + distance + ", " + test); JsonObject location = element.getAsJsonObject().get("end_location").getAsJsonObject(); String latitude = location.get("lat").toString(); String longitude = location.get("lng").toString(); //now I need to hit a different API and get CITY names from lat long //http://stackoverflow.com/questions/6548504/how-can-i-get-city-name-from-a-latitude-and-longitude-point //fortunately it shows me how here ^ System.out.println("TEST LOCATION LAT: " + latitude + " LONG: " + longitude); } } } catch (Exception e) { System.out.println("Error: " + e); } }
From source file:org.csware.ee.utils.Tools.java
public static String getSessionID(String path) { String[] sessionId = null;/* w w w .j a v a 2s.co m*/ try { // URL URL url = new URL(path); // HttpURLConnection HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); String session_value = urlConn.getHeaderField("Set-Cookie"); sessionId = session_value.split(";"); // urlConn.setConnectTimeout(5 * 1000); // urlConn.connect(); } catch (Exception ex) { ex.printStackTrace(); } return sessionId[0]; }
From source file:net.ae97.pokebot.extensions.scrolls.StatCommand.java
@Override public void runEvent(CommandEvent event) { try {/* w ww .j a v a2 s. co m*/ List<String> lines = new LinkedList<>(); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", "PokeBot - " + PokeBot.VERSION); conn.connect(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { lines.add(line); } } JsonParser parser = new JsonParser(); JsonElement element = parser.parse(StringUtils.join(lines, "\n")); JsonObject obj = element.getAsJsonObject(); JsonObject dataObject = obj.get("data").getAsJsonObject(); StringBuilder builder = new StringBuilder(); builder.append("Stats - "); builder.append("Online today: ").append(dataObject.get("onlinetoday").getAsInt()); builder.append(" - "); builder.append("Gold earned: ").append(dataObject.get("goldearned").getAsInt()); builder.append(" - "); builder.append("Games played: ").append(dataObject.get("gamesplayed").getAsInt()); builder.append(" - "); builder.append("Total users: ").append(dataObject.get("totalusers").getAsInt()); String message = builder.toString(); event.respond(message); } catch (IOException | JsonSyntaxException ex) { PokeBot.getLogger().log(Level.SEVERE, "Error on getting stats for Scrolls", ex); event.respond("Error on getting stats: " + ex.getLocalizedMessage()); } }
From source file:h2weibo.utils.filters.FlickrImageFilter.java
private String extraceFromShortURL(String input) { Pattern p = Pattern.compile("flic.kr/p/(\\w+)/?.*"); Matcher m = p.matcher(input); if (m.find()) { input = "http://www.flickr.com/photo.gne?short=" + m.group(1); String imageUrl = null;//from w w w . j a va 2 s .com try { URL url = new URL(input); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setInstanceFollowRedirects(false); conn.connect(); int code = conn.getResponseCode(); if (code == 302) { String loc = conn.getHeaderField("location"); imageUrl = extraceFromFullURL("http://www.flickr.com" + loc); } conn.disconnect(); } catch (Exception e) { log.error("Not able to handle flickr's short url/", e); } return imageUrl; } else { return null; } }
From source file:io.mingle.v1.Connection.java
public Response run(String comprehension) { String expr = "{ \"query\": \"" + comprehension + "\", \"limit\": 10000 }"; try {// w w w .jav a2 s . co m HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(expr, 0, expr.length()); out.flush(); out.close(); InputStream in = conn.getInputStream(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); byte[] chunk = new byte[4096]; int read = 0; while ((read = in.read(chunk)) > 0) { buf.write(chunk, 0, read); } in.close(); String str = buf.toString(); System.out.println("GOT JSON: " + str); return new Response(JSONValue.parse(str)); } catch (Exception e) { System.err.printf("failed to execute: %s\n", expr); e.printStackTrace(); } return null; }
From source file:weatherRoute.MapHandler.java
public ArrayList<Location> getCities(String origin, String destination) { ArrayList<Location> cities = new ArrayList<Location>(); origin = origin.replace(" ", ""); destination = destination.replace(" ", ""); String apiQuery = "https://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&key=AIzaSyDbWBUUbN6UHlG9auqFVGmN6WJY9HSe8YI"; try {//from w w w . ja va2s. c o m URL url = new URL(apiQuery); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); JsonParser jp = new JsonParser(); JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //You have to step through the ugly, JSON within array within JSON stuff. JsonArray stepsArray = root.getAsJsonObject().getAsJsonArray("routes").get(0).getAsJsonObject() .getAsJsonArray("legs").get(0).getAsJsonObject().getAsJsonArray("steps"); //loop through steps to get city locations for (JsonElement element : stepsArray) { //this gets a string value of the distance in miles String distance = element.getAsJsonObject().get("distance").getAsJsonObject().get("text") .toString(); if (distance.contains("mi")) { //parse return value and cast to a Double to be able to compare distance = distance.replace(" mi", ""); distance = distance.replace("\"", ""); Double test = Double.parseDouble(distance); //this limits out all the short .5 mile steps //should mostly get different cities now if (Double.compare(test, 10.0) > 0) { System.out.println("TEST DISTANCE: " + distance + ", " + test); JsonObject location = element.getAsJsonObject().get("end_location").getAsJsonObject(); String latitude = location.get("lat").toString(); String longitude = location.get("lng").toString(); Location tempLocation = new Location(Double.parseDouble(latitude), Double.parseDouble(longitude)); cities.add(tempLocation); //now I need to hit a different API and get CITY names from lat long //http://stackoverflow.com/questions/6548504/how-can-i-get-city-name-from-a-latitude-and-longitude-point //fortunately it shows me how here ^ //System.out.println("TEST LOCATION LAT: " + latitude + " LONG: " + longitude); } } } } catch (Exception e) { System.out.println("Error: " + e); } //testing(); return cities; }