Example usage for java.net URL URL

List of usage examples for java.net URL URL

Introduction

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

Prototype

public URL(String spec) throws MalformedURLException 

Source Link

Document

Creates a URL object from the String representation.

Usage

From source file:com.manning.blogapps.chapter10.examples.AuthGetJava.java

public static void main(String[] args) throws Exception {
    if (args.length < 3) {
        System.out.println("USAGE: authget <username> <password> <url>");
        System.exit(-1);//from  w w w  .ja va2s. com
    }
    String credentials = args[0] + ":" + args[1];

    URL url = new URL(args[2]);
    URLConnection conn = url.openConnection();

    conn.setRequestProperty("Authorization",
            "Basic " + new String(Base64.encodeBase64(credentials.getBytes())));

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String s = null;
    while ((s = in.readLine()) != null) {
        System.out.println(s);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
    SOAPConnection connection = sfc.createConnection();

    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage sm = mf.createMessage();

    SOAPHeader sh = sm.getSOAPHeader();
    SOAPBody sb = sm.getSOAPBody();
    sh.detachNode();//w w  w  .ja va  2  s.  c o  m
    QName bodyName = new QName("http://quoteCompany.com", "GetQuote", "d");
    SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
    QName qn = new QName("aName");
    SOAPElement quotation = bodyElement.addChildElement(qn);

    quotation.addTextNode("TextMode");

    System.out.println("\n Soap Request:\n");
    sm.writeTo(System.out);
    System.out.println();

    URL endpoint = new URL("http://yourServer.com");
    SOAPMessage response = connection.call(sm, endpoint);
    System.out.println(response.getContentDescription());
}

From source file:com.util.finalProy.java

/**
 * @param args the command line arguments
 *//*from w  ww. j  a v a2s.c o  m*/
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());
}

From source file:GetChannels.java

public static void main(String[] args) {
    System.out.println("Executing Get Channels");
    try {/*from w  w w.  ja  v  a  2s .c  om*/
        URL marketoSoapEndPoint = new URL("CHANGEME" + "?WSDL");
        String marketoUserId = "CHANGEME";
        String marketoSecretKey = "CHANGEME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsGetChannels params = new ParamsGetChannels();
        Tag tags = new Tag();
        ArrayOfString tagArray = new ArrayOfString();
        tagArray.getStringItems().add("Webinar");
        tagArray.getStringItems().add("Blog");
        tagArray.getStringItems().add("Tradeshow");
        tags.setValues(tagArray);

        MktowsPort port = service.getMktowsApiSoapPort();
        SuccessGetChannels result = port.getChannels(params, header);

        JAXBContext context = JAXBContext.newInstance(SuccessGetLead.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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();//from  ww w . j  a  va2  s .  c om
    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:SOAPRequest.java

public static void main(String[] args) {
    try {//ww  w.  j  a v a 2s  . c  om
        SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = sfc.createConnection();

        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage sm = mf.createMessage();

        SOAPHeader sh = sm.getSOAPHeader();
        SOAPBody sb = sm.getSOAPBody();
        sh.detachNode();
        QName bodyName = new QName("http://quoteCompany.com", "GetQuote", "d");
        SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
        QName qn = new QName("aName");
        SOAPElement quotation = bodyElement.addChildElement(qn);

        quotation.addTextNode("TextMode");

        System.out.println("\n Soap Request:\n");
        sm.writeTo(System.out);
        System.out.println();

        URL endpoint = new URL("http://yourServer.com");
        SOAPMessage response = connection.call(sm, endpoint);
        System.out.println(response.getContentDescription());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:crawlercommons.sitemaps.SiteMapTester.java

public static void main(String[] args) throws IOException, UnknownFormatException {
    if (args.length < 1) {
        LOG.error("Usage: SiteMapTester <URL_TO_TEST> [MIME_TYPE]");
    } else {/*  ww  w  .jav a 2  s  .c  o m*/
        URL url = new URL(args[0]);
        String mt = (args.length > 1) ? args[1] : null;

        parse(url, mt);
    }
}

From source file:com.gemini.httpclienttest.HttpClientTestMain.java

public static void main(String[] args) {
    //authenticate with the server
    URL url;/*from  w w w  .j av  a  2 s .c  o  m*/
    try {
        url = new URL("http://198.11.209.34:5000/v2.0/tokens");
    } catch (MalformedURLException ex) {
        System.out.printf("Invalid Endpoint - not a valid URL {}", "http://198.11.209.34:5000/v2.0");
        return;
    }
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    try {
        HttpPost httpPost = new HttpPost(url.toString());
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity strEntity = new StringEntity(
                "{\"auth\":{\"tenantName\":\"Gemini-network-prj\",\"passwordCredentials\":{\"username\":\"sri\",\"password\":\"srikumar12\"}}}");
        httpPost.setEntity(strEntity);
        //System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            //get the response status code 
            String respStatus = response.getStatusLine().getReasonPhrase();

            //get the response body
            int bytes = response.getEntity().getContent().available();
            InputStream body = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(body));
            String line;
            StringBuffer sbJSON = new StringBuffer();
            while ((line = in.readLine()) != null) {
                sbJSON.append(line);
            }
            String json = sbJSON.toString();
            EntityUtils.consume(response.getEntity());

            GsonBuilder gsonBuilder = new GsonBuilder();
            Object parsedJson = gsonBuilder.create().fromJson(json, Object.class);
            System.out.printf("Parsed json is of type %s\n\n", parsedJson.getClass().toString());
            if (parsedJson instanceof com.google.gson.internal.LinkedTreeMap) {
                com.google.gson.internal.LinkedTreeMap treeJson = (com.google.gson.internal.LinkedTreeMap) parsedJson;
                if (treeJson.containsKey("id")) {
                    String s = (String) treeJson.getOrDefault("id", "no key provided");
                    System.out.printf("\n\ntree contained id %s\n", s);
                } else {
                    System.out.printf("\n\ntree does not contain key id\n");
                }
            }
        } catch (IOException ex) {
            System.out.print(ex);
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        System.out.print(ex);
    } finally {
        //lots of exceptions, just the connection and exit
        try {
            httpclient.close();
        } catch (IOException | NoSuchMethodError ex) {
            System.out.print(ex);
            return;
        }
    }
}

From source file:net.infstudio.inflauncher.Main.java

public static void main(String[] args) {
    //TODO Test/*from   w w w  . j  a  v  a2 s. co m*/
    InfinityDownloader.logger.info("Hello world!");
    try {
        URL mcURL = new URL("http://s3.amazonaws.com/Minecraft.Download/versions/1.10.2/1.10.2.json");
        FileUtils.copyInputStreamToFile(mcURL.openStream(), new File("1.10.2.json"));
        InfinityDownloader.logger.info("Ping to http://stackoverflow.com: time="
                + URLConnectionTimer.testTime("http://stackoverflow.com"));
    } catch (IOException e) {
        LogManager.getLogger("InfinityLauncher").error(e);
    }

}

From source file:com.trustedbank.TrustedBankStart.java

/**
 * Main function, starts the jetty server.
 * /*from www  .  j av  a2 s  .  c o m*/
 * @param args
 */
public static void main(String[] args) {
    Server jettyServer = null;
    try {
        URL jettyConfig = new URL("file:src/main/resources/jetty-config.xml");
        if (jettyConfig == null) {
            log.fatal("Unable to locate jetty-test-config.xml on the classpath");
        }
        jettyServer = new Server(jettyConfig);
        jettyServer.start();
    } catch (Exception e) {
        log.fatal("Could not start the Jetty server: " + e);
        if (jettyServer != null) {
            try {
                jettyServer.stop();
            } catch (InterruptedException e1) {
                log.fatal("Unable to stop the jetty server: " + e1);
            }
        }
    }
}