Example usage for java.net HttpURLConnection setRequestProperty

List of usage examples for java.net HttpURLConnection setRequestProperty

Introduction

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

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:bakuposter.gcm.server.POST2GCMessage.java

public static void post(String apiKey, Content content) {

    try {/* w ww  .ja  v a2 s .com*/
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);
        conn.setDoOutput(true);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(content.getRegistration_ids().get(0));
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        mapper.writeValue(wr, content);
        wr.flush();
        wr.close();
        int responseCode = conn.getResponseCode();
        System.out.println("responseCode = " + responseCode);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static String simplePost(String url, Bundle params, String method)
        throws MalformedURLException, IOException {
    OutputStream os;//w ww .jav  a 2  s. c  om

    System.setProperty("http.keepAlive", "false");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent");

    conn.setRequestMethod(method);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    //conn.setRequestProperty("Connection", "Keep-Alive");

    conn.connect();

    os = new BufferedOutputStream(conn.getOutputStream());
    os.write(encodePostParams(params).getBytes());
    os.flush();

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:Main.java

public static String openUrl(String url, String method, Bundle params) {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }/*from   w w  w. j  a v  a2 s.com*/
    String response = "";
    try {
        Log.d(LOG_TAG, method + " URL: " + url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                System.getProperties().getProperty("http.agent") + " RenrenAndroidSDK");
        if (!method.equals("GET")) {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
        }

        response = read(conn.getInputStream());
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage());
        throw new RuntimeException(e.getMessage(), e);
    }
    return response;
}

From source file:Main.java

public static String request(String httpUrl, String httpArg) {
    BufferedReader reader = null;
    String result = null;//from  ww w  . j a  va  2  s  .co  m
    StringBuffer sbf = new StringBuffer();
    httpUrl = httpUrl + "?" + httpArg;

    try {
        URL url = new URL(httpUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("apikey", "2ffbcae4d025b6c109af30d7de2d7c09");
        connection.connect();
        InputStream is = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sbf.append(strRead);
            sbf.append("\r\n");
        }
        reader.close();
        result = sbf.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.android.nunes.sophiamobile.gsm.GcmSender.java

public static void enviar(String msg, String token) {

    try {//from www. j  a  va  2s .c om
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", msg.trim());
        // Where to send GCM message.
        if (token != null) {
            jGcmData.put("to", token.trim());
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        System.out.println(resp);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.google.cloud.runtime.jetty.util.HttpUrlUtil.java

/**
 * Open a new {@link HttpURLConnection} to the provided URI.
 * <p>/*from w w w . j  a va 2s .c o m*/
 * Note: will also set the 'User-Agent' to {@code jetty-runtime/gcloud-util-core}
 * </p>
 *
 * @param uri the URI to open to
 * @return the open HttpURLConnection
 * @throws IOException if unable to open the connection
 */
public static HttpURLConnection openTo(URI uri) throws IOException {
    log.info("HttpUrlUtil.openTo(" + uri + ")");
    HttpURLConnection http = (HttpURLConnection) uri.toURL().openConnection();
    http.setRequestProperty("User-Agent", "jetty-runtime/gcloud-util-core");
    return http;
}

From source file:Main.java

public static HttpURLConnection openUrlConnection(String url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setUseCaches(false);/*from w  w  w .  jav a  2 s .  co m*/
    conn.setChunkedStreamingMode(0);
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.connect();
    return conn;
}

From source file:Main.java

private static HttpURLConnection getConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setDoInput(true);/*from  w  w w .ja  v a  2 s .c o m*/
    conn.setDoOutput(true);
    conn.setRequestProperty("Accept", "text/xml");
    return conn;
}

From source file:de.jetwick.util.Translate.java

public static String download(String urlAsString) {
    try {//from  w  ww.j a  v a 2  s  .c o m
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        hConn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
        hConn.addRequestProperty("Referer", "http://jetsli.de/crawler");

        hConn.setConnectTimeout(2000);
        hConn.setReadTimeout(2000);
        InputStream is = hConn.getInputStream();
        if ("gzip".equals(hConn.getContentEncoding()))
            is = new GZIPInputStream(is);

        return getInputStream(is);
    } catch (Exception ex) {
        return "";
    }
}

From source file:Main.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from w w w  . j a  v  a2  s.com*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        // use method override
        params.putString("method", method);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }

    return response;
}