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:pushandroid.POST2GCM.java

public static void post(Content content) {

    try {//from   w w w  .j ava2 s  .  c  om

        // 1. URL
        URL url = new URL(URL);

        // 2. Open connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Specify POST method
        conn.setRequestMethod("POST");

        // 4. Set the headers
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);

        // 5. Add JSON data into POST request body
        //`5.1 Use Jackson object mapper to convert Contnet object into JSON
        ObjectMapper mapper = new ObjectMapper();

        // 5.2 Get connection output stream
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

        // 5.3 Copy Content "JSON" into
        mapper.writeValue(wr, content);

        // 5.4 Send the request
        wr.flush();

        // 5.5 close
        wr.close();

        // 6. Get the response
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

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

        // 7. Print result
        System.out.println(response.toString());

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

From source file:com.asual.lesscss.ResourceUtils.java

public static byte[] readBinaryUrl(URL source) throws IOException {
    byte[] result;
    try {//from w  w w  .  j ava  2s .  c  o  m
        URLConnection urlc = source.openConnection();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        InputStream input = urlc.getInputStream();
        try {
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while ((bytesRead = input.read(buffer)) != -1) {
                byteStream.write(buffer, 0, bytesRead);
            }
            result = byteStream.toByteArray();
        } finally {
            byteStream.close();
            input.close();
        }
    } catch (IOException e) {
        logger.error("Can't read '" + source.getFile() + "'.");
        throw e;
    }
    return result;
}

From source file:com.microsoft.azure.engagement.ws.VideoParser.java

/**
 * Method that returns the result object
 *
 * @param urlString The url to parse/* w  w w  . java2  s .c o m*/
 * @return The result object
 */
private static final JSONObject getJsonObject(String urlString) {
    Log.d(VideoParser.TAG, "Parse URL: " + urlString);

    InputStream inputStream = null;

    try {
        final URL url = new URL(urlString);
        final URLConnection urlConnection = url.openConnection();

        inputStream = new BufferedInputStream(urlConnection.getInputStream());
        final BufferedReader reader = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream(), "utf-8"), 8);
        final StringBuilder sb = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        final String json = sb.toString();
        return new JSONObject(json);
    } catch (Exception e) {
        Log.w(VideoParser.TAG, "Failed to parse the json for media list", e);
        return null;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.w(VideoParser.TAG, "JSON feed closed", e);
            }
        }
    }

}

From source file:com.mopaas_mobile.http.BaseHttpRequester.java

public static String doPOST(String urlstr, List<BasicNameValuePair> params) throws IOException {
    String result = null;/*from   w  w w. ja va  2  s. co m*/
    URL url = new URL(urlstr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //       connection.setRequestProperty("token",token);
    connection.setConnectTimeout(30000);
    connection.setReadTimeout(30000);
    connection.connect();

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());

    String content = "";
    if (params != null && params.size() > 0) {
        for (int i = 0; i < params.size(); i++) {
            content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8")
                    + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8");
        }
        out.writeBytes(content.substring(1));
    }

    out.flush();
    out.close();
    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = br.read()) != -1) {
        b.append((char) ch);
    }
    result = b.toString().trim();
    connection.disconnect();
    return result;
}

From source file:Main.java

public static void server2mobile(Context context, String type) {

    String serverPath = "http://shaunrain.zicp.net/FileUp/QueryServlet?type=" + type;
    try {/*from   w  ww .j  a  v  a2  s .c  om*/
        URL url = new URL(serverPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10000);
        conn.setRequestMethod("GET");

        int code = conn.getResponseCode();
        Log.d("code", code + "");
        if (code == 200) {
            InputStream is = conn.getInputStream();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];

            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            conn.disconnect();

            String result = new String(baos.toByteArray());
            String[] results = result.split("[$]");
            for (String r : results) {
                if (r.length() != 0) {
                    URL json = new URL(r);
                    HttpURLConnection con = (HttpURLConnection) json.openConnection();
                    con.setConnectTimeout(5000);
                    con.setRequestMethod("GET");
                    int co = con.getResponseCode();
                    if (co == 200) {
                        File jsonFile;
                        if (r.endsWith("clear.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/clear.json");
                        } else if (r.endsWith("crowd.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/crowd.json");
                        } else if (r.endsWith("trouble.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/trouble.json");
                        } else {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/control.json");
                        }

                        if (jsonFile.exists())
                            jsonFile.delete();
                        jsonFile.createNewFile();
                        try (BufferedReader reader = new BufferedReader(
                                new InputStreamReader(con.getInputStream(), "gb2312"));
                                BufferedWriter writer = new BufferedWriter(new FileWriter(jsonFile));) {
                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                writer.write(line);
                            }
                        }

                    }
                    con.disconnect();
                }
            }

        }

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

}

From source file:ilearnrw.utils.ServerHelperClass.java

public static String sendPost(String link, String urlParameters) throws Exception {
    String url = baseUrl + link;// w w  w  .  ja  v  a2s .c  o  m

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("Authorization", userNamePasswordBase64("api", "api"));

    con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    con.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF8");

    wr.write(urlParameters);
    wr.flush();
    wr.close();
    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(), "UTF-8"));
    String inputLine;
    StringBuffer response = new StringBuffer();

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

    return response.toString();
}

From source file:massbank.svn.MSDBUpdateUtil.java

/**
 *
 *///from www .  jav a2  s .c om
public static boolean updateSubStructData(String serverUrl) {
    boolean ret = true;
    String cgiUrl = serverUrl + "cgi-bin/GenSubstructure.cgi";
    try {
        URL url = new URL(cgiUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(10 * 1000);
        con.setReadTimeout(60 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line = "";
        StringBuilder res = new StringBuilder();
        while ((line = in.readLine()) != null) {
            res.append(line);
        }
        if (res.indexOf("OK") == -1) {
            ret = false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        ret = false;
    }
    return ret;
}

From source file:com.facebook.fresco.sample.urlsfetcher.ImageUrlsFetcher.java

@Nullable
private static String downloadContentAsString(String urlString) throws IOException {
    InputStream is = null;/*www.  ja  v  a  2s. c  o  m*/
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID);
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        if (response != HttpStatus.SC_OK) {
            FLog.e(TAG, "Album request returned %s", response);
            return null;
        }
        is = conn.getInputStream();
        return readAsString(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:be.solidx.hot.utils.IOUtils.java

public static InputStream loadResourceNoCache(URL path) throws IOException {
    URLConnection resConn = path.openConnection();
    // !!! needed to avoid jvm resource catching
    resConn.setUseCaches(false);//w  w  w.  j  a  v  a  2  s. c o  m
    return resConn.getInputStream();
}

From source file:mdretrieval.FileFetcher.java

public static InputStream fetchFileFromUrl(String urlString) {

    InputStream inputStream = null;

    Proxy proxy = ServerConstants.isProxyEnabled
            ? new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ServerConstants.hostname, ServerConstants.port))
            : Proxy.NO_PROXY;/*  w  w w  .j a  v  a  2  s .  c  o  m*/

    URL url;
    try {
        url = new URL(urlString);
        url.openConnection();

        if (proxy != Proxy.NO_PROXY && proxy.type() != Proxy.Type.DIRECT) {
            inputStream = url.openConnection(proxy).getInputStream();
        } else {
            inputStream = url.openConnection().getInputStream();
        }
    } catch (MalformedURLException e) {
        GUIrefs.displayAlert("Invalid URL " + urlString + "- \\n malformed expression");
        e.printStackTrace();
        inputStream = null;
    } catch (IOException ioe) {
        GUIrefs.displayAlert("Cannot read from " + StringUtilities.escapeQuotes(urlString) + "- IOException");
        ioe.printStackTrace();
        inputStream = null;
    }

    return inputStream;
}