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:javaphpmysql.JavaPHPMySQL.java

public static void sendPost() {
    //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   ww w . j  a v a 2s .c om*/
        //Codificar el json a URL
        jsonString = URLEncoder.encode(jsonString, "UTF-8");
        //Generar la URL
        String url = SERVER_PATH + "listenPost.php";
        //Creamos un nuevo objeto URL con la url donde queremos enviar el JSON
        URL obj = new URL(url);
        //Creamos un objeto de conexin
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        //Aadimos la cabecera
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        //Creamos los parametros para enviar
        String urlParameters = "json=" + jsonString;
        // Enviamos los datos por POST
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        //Capturamos la respuesta del servidor
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        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);
        }
        //Mostramos la respuesta del servidor por consola
        System.out.println(response);
        //cerramos la conexin
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.meetingninja.csse.database.GroupDatabaseAdapter.java

private static String sendSingleEdit(String payload) throws IOException {
    String _url = getBaseUri().build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(IRequest.PUT);
    addRequestHeader(conn, false);//from   w  w w .  ja v a  2  s.co  m
    sendPostPayload(conn, payload);
    return getServerResponse(conn);

}

From source file:mobisocial.musubi.social.FacebookFriendFetcher.java

public static byte[] getImageFromURL(String remoteUrl) {
    try {//  w w w  .j av  a  2s . co  m
        // Grab the content
        URL url = new URL(remoteUrl);
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();

        // Read the content chunk by chunk
        BufferedInputStream bis = new BufferedInputStream(is, 8192);
        ByteArrayBuffer baf = new ByteArrayBuffer(0);
        byte[] chunk = new byte[CHUNK_SIZE];
        int current = bis.read(chunk);
        while (current != -1) {
            baf.append(chunk, 0, current);
            current = bis.read(chunk);
        }
        return baf.toByteArray();
    } catch (IOException e) {
        Log.e(TAG, "HTTP error", e);
    }
    return null;
}

From source file:subhan.portal.config.Util.java

public static void downloadFromUrl(String downloadUrl, String fileName) throws IOException {
    File root = android.os.Environment.getExternalStorageDirectory(); // path ke sdcard

    File dir = new File(root.getAbsolutePath() + "/youread"); // path ke folder

    if (dir.exists() == false) { // cek folder eksistensi
        dir.mkdirs(); // kalau belum ada, dibuat
    }/*from ww  w.j  av  a  2  s.c om*/

    URL url = new URL(downloadUrl); // you can write here any link
    File file = new File(dir, fileName);

    // Open a connection to that URL. 
    URLConnection ucon = url.openConnection();

    // Define InputStreams to read from the URLConnection. 
    InputStream is = ucon.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);

    // Read bytes to the Buffer until there is nothing more to read(-1).
    ByteArrayBuffer baf = new ByteArrayBuffer(5000);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }

    // Convert the Bytes read to a String. 
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(baf.toByteArray());
    fos.flush();
    fos.close();
}

From source file:com.rmtheis.yandtran.YandexTranslatorAPI.java

/**
 * Forms an HTTPS request, sends it using GET method and returns the result of the request as a String.
 * /*w  w w.  ja va 2  s . co  m*/
 * @param url The URL to query for a String response.
 * @return The translated String.
 * @throws Exception on error.
 */
private static String retrieveResponse(final URL url) throws Exception {
    final HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", "text/plain; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("GET");

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Yandex API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}