Example usage for java.net HttpURLConnection connect

List of usage examples for java.net HttpURLConnection connect

Introduction

In this page you can find the example usage for java.net HttpURLConnection connect.

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:edu.wfu.inotado.helper.RestClientHelper.java

public String getFromService(String serviceName, String urlStr) throws Exception {

    OAuthConsumer consumer = oauthHelper.getConsumer(serviceName);
    URL url;/*from www .  ja v a2 s .c  o m*/
    url = new URL(urlStr);
    HttpURLConnection request = (HttpURLConnection) url.openConnection();

    consumer.sign(request);

    log.info("Sending request...");
    request.connect();

    InputStream in = (InputStream) request.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String result, line = reader.readLine();
    result = line;
    while ((line = reader.readLine()) != null) {
        result += line;
    }
    log.debug("Respone: " + result);
    log.info("Response: " + request.getResponseCode() + " " + request.getResponseMessage());

    return result;
}

From source file:com.WeatherProxy.java

private void getWeather(String lat, String lng) {
    weatherNow = "";
    String apiUrl = "https://api.forecast.io/forecast/";
    String apiKey = "fad007e59cd36e504fa337d946feb7d2";
    String urlString = apiUrl + apiKey + "/" + lat + "," + lng;

    try {//from  w ww  .  ja  va  2  s . c om
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.connect();

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        // The body of the response is available as an input stream.
        // Using BufferedReader is good practice for efficient I/O, because it
        // takes lots of little reads and does fewer larger actual I/O
        // operations.  It doesn't make much difference in this case,
        // since we only do one I/O.  But it's still good practice.
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        // api.forecast.io returns a single (very long) line of JSON.
        weatherNow += br.readLine();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        this.weatherNow = "{ 'error': 'MalformedURLException' }";
    } catch (IOException e) {
        e.printStackTrace();
        this.weatherNow = "{ 'error': 'IOException' }";
    }
}

From source file:org.jboss.as.test.integration.management.console.WebConsoleRedirectionTestCase.java

private HttpURLConnection getConnection() throws Exception {
    final URL url = new URL("http://" + TestSuiteEnvironment.getServerAddress() + ":"
            + TestSuiteEnvironment.getServerPort() + "/");
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    assertNotNull(connection);/*w w  w.java2s .  co m*/
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod(HttpGet.METHOD_NAME);
    connection.connect();
    return connection;
}

From source file:it.openyoureyes.test.panoramio.Panoramio.java

public List<GeoItem> examinePanoramio(Location current, double distance, Drawable myImage, Intent intent) {
    ArrayList<GeoItem> result = new ArrayList<GeoItem>();

    /*/*from w w w .  j  a  v a  2  s .co  m*/
     * var requiero_fotos = new Json.Remote(
     * "http://www.panoramio.com/map/get_panoramas.php?order=popularity&
     * set=
     * full&from=0&to=10&minx=-5.8&miny=42.59&maxx=-5.5&maxy=42.65&size=
     * medium "
     */
    Location loc1 = new Location("test");
    Location loc2 = new Location("test_");
    AbstractGeoItem.calcDestination(current.getLatitude(), current.getLongitude(), 225, distance / 2, loc1);
    AbstractGeoItem.calcDestination(current.getLatitude(), current.getLongitude(), 45, distance / 2, loc2);
    try {
        URL url = new URL(
                "http://www.panoramio.com/map/get_panoramas.php?order=popularity&set=full&from=0&to=10&minx="
                        + loc1.getLongitude() + "&miny=" + loc1.getLatitude() + "&maxx=" + loc2.getLongitude()
                        + "&maxy=" + loc2.getLatitude() + "&size=thumbnail");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuffer buf = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buf.append(line + " ");
        }
        reader.close();
        is.close();
        conn.disconnect();
        // while (is.read(buffer) != -1);
        String jsontext = buf.toString();
        Log.d("Json Panoramio", jsontext);
        JSONObject entrie = new JSONObject(jsontext);
        JSONArray arr = entrie.getJSONArray("photos");
        for (int i = 0; i < arr.length(); i++) {
            JSONObject panoramioObj = arr.getJSONObject(i);
            double longitude = panoramioObj.getDouble("longitude");
            double latitude = panoramioObj.getDouble("latitude");
            String urlFoto = panoramioObj.getString("photo_file_url");
            String idFoto = panoramioObj.getString("photo_id");
            Bundle bu = intent.getExtras();
            if (bu == null)
                bu = new Bundle();
            bu.putString("id", idFoto);
            intent.replaceExtras(bu);
            BitmapDrawable bb = new BitmapDrawable(downloadFile(urlFoto));
            PanoramioItem item = new PanoramioItem(latitude, longitude, false, bb, intent);
            result.add(item);
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return result;

}

From source file:com.smedic.tubtub.JsonAsyncTask.java

@Override
protected ArrayList<String> doInBackground(String... params) {

    //encode param to avoid spaces in URL
    String encodedParam = "";
    try {//from  www.  j a  va2s.  co  m
        encodedParam = URLEncoder.encode(params[0], "UTF-8").replace("+", "%20");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    ArrayList<String> items = new ArrayList<>();
    try {
        URL url = new URL(
                "http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=" + encodedParam);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();
        // gets the server json data
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream()));

        String next;
        while ((next = bufferedReader.readLine()) != null) {

            if (checkJson(next) == JSON_ERROR) {
                //if not valid, remove invalid parts (this is simple hack for URL above)
                next = next.substring(19, next.length() - 1);
            }

            JSONArray ja = new JSONArray(next);

            for (int i = 0; i < ja.length(); i++) {

                if (ja.get(i) instanceof JSONArray) {
                    JSONArray ja2 = ja.getJSONArray(i);

                    for (int j = 0; j < ja2.length(); j++) {

                        if (ja2.get(j) instanceof JSONArray) {
                            String suggestion = ((JSONArray) ja2.get(j)).getString(0);
                            //Log.d(TAG, "Suggestion: " + suggestion);
                            items.add(suggestion);
                        }
                    }
                } else if (ja.get(i) instanceof JSONObject) {
                    //Log.d(TAG, "json object");
                } else {
                    //Log.d(TAG, "unknown object");
                }
            }
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
    return items;
}

From source file:org.apache.olingo.odata2.fit.basic.FitLoadTest.java

@Test
public void useJavaHttpClient() throws IOException {
    final URI uri = URI.create(getEndpoint().toString() + "$metadata");
    for (int i = 0; i < LOOP_COUNT; i++) {
        HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty(HttpHeaders.ACCEPT, HttpContentType.WILDCARD);
        connection.connect();
        assertEquals(HttpStatusCodes.OK.getStatusCode(), connection.getResponseCode());
        assertEquals(HttpContentType.APPLICATION_XML_UTF8, connection.getContentType());
    }/*from   w  w w .j  av  a 2s  .c o m*/
}

From source file:com.google.apphosting.vmruntime.jetty9.VmRuntimeJettyKitchenSinkTest.java

/**
 * Tests that app.yaml is protected//  ww w.j a v a2 s  . c  om
 */
public void testAppYamlHidden() throws Exception {
    HttpURLConnection connection = (HttpURLConnection) createUrl("/app.yaml").openConnection();
    connection.connect();
    assertEquals(404, connection.getResponseCode());
}

From source file:Servlet.Change.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* www.  j  a v a2 s .c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        //grabbing the event parameter
        String eventUrl = request.getParameter("eventUrl");
        System.out.print(eventUrl);

        //Obtaining authority of event
        OAuthConsumer consumer = new DefaultOAuthConsumer("test6-40942", "oQ4q4oBiv9y4jPr7");
        URL url = new URL(eventUrl);
        HttpURLConnection requestUrl = (HttpURLConnection) url.openConnection();
        consumer.sign(requestUrl);
        requestUrl.connect();

        //Reading in the xml file as a string
        String result = null;
        StringBuilder sb = new StringBuilder();
        InputStream is = new BufferedInputStream(requestUrl.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String inputLine = "";
        while ((inputLine = br.readLine()) != null) {
            sb.append(inputLine);
        }

        result = sb.toString();

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(result));

        //parsing elements by name tags from event url
        Document doc = builder.parse(src);
        String creatorName = doc.getElementsByTagName("fullName").item(0).getTextContent();
        String companyName = doc.getElementsByTagName("name").item(0).getTextContent();
        String edition = doc.getElementsByTagName("editionCode").item(0).getTextContent();
        String returnUrl = doc.getElementsByTagName("returnUrl").item(0).getTextContent();

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost xmlResponse = new HttpPost(returnUrl);
        StringEntity input = new StringEntity(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><result><success>true</success><message>Account change successful</message>");
        input.setContentType("text/xml");
        xmlResponse.setEntity(input);
        httpClient.execute(xmlResponse);

    } catch (OAuthMessageSignerException ex) {
        Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthExpectationFailedException ex) {
        Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthCommunicationException ex) {
        Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Servlet.Notification.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w w  w .  j a  v a2 s  .  com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        //grabbing the event parameter
        String eventUrl = request.getParameter("eventUrl");
        System.out.print(eventUrl);

        //Obtaining authority of event
        OAuthConsumer consumer = new DefaultOAuthConsumer("test6-40942", "oQ4q4oBiv9y4jPr7");
        URL url = new URL(eventUrl);
        HttpURLConnection requestUrl = (HttpURLConnection) url.openConnection();
        consumer.sign(requestUrl);
        requestUrl.connect();

        //Reading in the xml file as a string
        String result = null;
        StringBuilder sb = new StringBuilder();
        InputStream is = new BufferedInputStream(requestUrl.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String inputLine = "";
        while ((inputLine = br.readLine()) != null) {
            sb.append(inputLine);
        }

        result = sb.toString();

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(result));

        Document doc = builder.parse(src);
        String creatorName = doc.getElementsByTagName("fullName").item(0).getTextContent();
        String companyName = doc.getElementsByTagName("name").item(0).getTextContent();
        String edition = doc.getElementsByTagName("editionCode").item(0).getTextContent();
        String returnUrl = doc.getElementsByTagName("returnUrl").item(0).getTextContent();

        //parsing elements by name tags from event url
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost xmlResponse = new HttpPost(returnUrl);
        StringEntity input = new StringEntity(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><result><success>true</success><message>Account change successful</message>");
        input.setContentType("text/xml");
        xmlResponse.setEntity(input);
        httpClient.execute(xmlResponse);

    } catch (OAuthMessageSignerException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthExpectationFailedException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthCommunicationException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:net.ae97.pokebot.extensions.scrolls.PriceCommand.java

@Override
public void runEvent(CommandEvent event) {
    if (event.getArgs().length == 0) {
        event.respond("Usage: .price [name]");
        return;/*from   w w  w. j a  v a 2  s  . co  m*/
    }

    String[] name = event.getArgs();
    try {
        URL playerURL = new URL(url.replace("{name}", StringUtils.join(name, "%20")));
        List<String> lines = new LinkedList<>();
        HttpURLConnection conn = (HttpURLConnection) playerURL.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();

        String result = obj.get("msg").getAsString();
        if (!result.equalsIgnoreCase("success")) {
            event.respond("Scroll not found");
            return;
        }
        JsonObject dataObject = obj.get("data").getAsJsonArray().get(0).getAsJsonObject();

        StringBuilder builder = new StringBuilder();

        JsonObject buyObj = dataObject.getAsJsonObject("buy");
        JsonObject sellObj = dataObject.getAsJsonObject("sell");
        JsonObject bmObj = dataObject.getAsJsonObject("bm");

        builder.append("Buy: ").append(buyObj.get("price").getAsInt()).append(" Gold - ");
        builder.append("Sell: ").append(sellObj.get("price").getAsInt()).append(" Gold - ");
        builder.append("Black Market: ").append(bmObj.get("price").getAsInt()).append(" Gold");
        String[] message = builder.toString().split("\n");
        for (String msg : message) {
            event.respond("" + msg);
        }

    } catch (IOException | JsonSyntaxException | IllegalStateException ex) {
        PokeBot.getLogger().log(Level.SEVERE,
                "Error on getting scroll for Scrolls for '" + StringUtils.join(event.getArgs(), " ") + "'", ex);
        event.respond("Error on getting scroll: " + ex.getLocalizedMessage());

    }
}