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:com.captix.scan.social.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from   w  w w .ja 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 {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            @SuppressWarnings("deprecation")
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).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:com.zf.util.Post_NetNew.java

/**
 * ?/*from   w ww  .  j a v  a 2 s  .c o  m*/
 * 
 * @param pams
 * @param ip
 * @param port
 * @return
 * @throws Exception
 */
public static String pn(Map<String, String> pams, String ip, int port) throws Exception {
    if (null == pams) {
        return "";
    }
    InetSocketAddress addr = new InetSocketAddress(ip, port);
    Proxy proxy = new Proxy(Type.HTTP, addr);
    String strtmp = "url";
    URL url = new URL(pams.get(strtmp));
    pams.remove(strtmp);
    strtmp = "body";
    String body = pams.get(strtmp);
    pams.remove(strtmp);
    strtmp = "POST";
    if (StringUtils.isEmpty(body))
        strtmp = "GET";
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(proxy);
    httpConn.setConnectTimeout(30000);
    httpConn.setReadTimeout(30000);
    httpConn.setUseCaches(false);
    httpConn.setRequestMethod(strtmp);
    for (String pam : pams.keySet()) {
        httpConn.setRequestProperty(pam, pams.get(pam));
    }
    if ("POST".equals(strtmp)) {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
        dos.writeBytes(body);
        dos.flush();
    }
    int resultCode = httpConn.getResponseCode();
    StringBuilder sb = new StringBuilder();
    sb.append(resultCode).append("\n");
    String readLine;
    InputStream stream;
    try {
        stream = httpConn.getInputStream();
    } catch (Exception ignored) {
        stream = httpConn.getErrorStream();
    }
    try {
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        while ((readLine = responseReader.readLine()) != null) {
            sb.append(readLine).append("\n");
        }
    } catch (Exception ignored) {
    }

    return sb.toString();
}

From source file:com.amazon.pay.impl.Util.java

/**
 * This method uses HttpURLConnection instance to make requests.
 *
 * @param method The HTTP method (GET,POST,PUT,etc.).
 * @param url The URL/*  w  w  w  . java2s .c  o  m*/
 * @param urlParameters URL Parameters
 * @param headers Header key-value pairs
 * @return ResponseData
 * @throws IOException
 */
public static ResponseData httpSendRequest(String method, String url, String urlParameters,
        Map<String, String> headers) throws IOException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    if (headers != null && !headers.isEmpty()) {
        for (String key : headers.keySet()) {
            con.setRequestProperty(key, headers.get(key));
        }
    }
    con.setDoOutput(true);
    con.setRequestMethod(method);
    if (urlParameters != null) {
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
    }
    int responseCode = con.getResponseCode();

    BufferedReader in;
    if (responseCode != 200) {
        in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
    } else {
        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine).append(LINE_SEPARATOR);
    }
    in.close();
    return new ResponseData(responseCode, response.toString());
}

From source file:com.facebook.android.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * 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/*w  w  w  . j  a  va  2 s  .c  o m*/
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
@Deprecated
public static String openUrl(String url, String method, Bundle params) throws IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Utility.logd("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            Object parameter = params.get(key);
            if (parameter instanceof byte[]) {
                dataparams.putByteArray(key, (byte[]) parameter);
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();

        os = new BufferedOutputStream(conn.getOutputStream());

        try {
            os.write(("--" + strBoundary + endLine).getBytes());
            os.write((encodePostBody(params, strBoundary)).getBytes());
            os.write((endLine + "--" + strBoundary + endLine).getBytes());

            if (!dataparams.isEmpty()) {

                for (String key : dataparams.keySet()) {
                    os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                    os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                    os.write(dataparams.getByteArray(key));
                    os.write((endLine + "--" + strBoundary + endLine).getBytes());

                }
            }
            os.flush();
        } finally {
            os.close();
        }
    }

    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:com.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * 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/* w w w  .j  a v a  2  s.  co m*/
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
@SuppressWarnings("deprecation")
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).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 httpPost(String urlStr, List<NameValuePair> params) {

    String paramsEncoded = "";
    if (params != null) {
        paramsEncoded = URLEncodedUtils.format(params, "UTF-8");
    }// ww  w.j a  va  2s.c om

    String result = null;
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;
    try {
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Charset", "utf-8");
        DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
        dop.writeBytes(paramsEncoded);
        dop.flush();
        dop.close();

        in = new InputStreamReader(connection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }
        result = strBuffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return result;
}

From source file:com.andrious.btc.data.jsonUtils.java

private static HttpURLConnection urlConnect(String urlString) throws IOException {

    URL url = new URL(urlString);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("GET");

    conn.setRequestProperty("Accept", "application/json");

    int response = conn.getResponseCode();

    if (response != HttpURLConnection.HTTP_OK) {

        if (!handleResponse(response, conn)) {

            throw new RuntimeException("Failed : HTTP error code : " + response);
        }//from w w  w  . ja  v  a2 s.  com
    }

    return conn;
}

From source file:com.bpd.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * 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/*from   ww  w  .jav a  2s  .c  o m*/
 * @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 {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    // Try to get filename key
    String filename = params.getString("filename");

    // If found
    if (filename != null) {
        // Remove from params
        params.remove("filename");
    }

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + ((filename != null) ? filename : key)
                        + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).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:com.thyn.backend.gcm.GcmSender.java

public static String addDeviceToDeviceGroup(String notification_key_name, String notification_key,
        String registration_token) {
    String resp = null;/*www  .j a v a 2  s.c  o  m*/
    try {
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();

        // Where to send GCM message.
        if (notification_key_name != null && registration_token != null) {
            jGcmData.put("operation", "add");
            jGcmData.put("notification_key_name", notification_key_name.trim());
            jGcmData.put("notification_key", notification_key.trim());
            jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]"));
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/notification");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("project_id", SENDER_ID);
        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();
        resp = IOUtils.toString(inputStream);

    } catch (IOException e) {
        Logger.logError("Unable to add Device to Device group.", e);

    }
    return resp;
}

From source file:it.unicaradio.android.gcm.GcmServerRpcCall.java

/**
 * @param url//from  www .  j  a va  2s. c om
 * @param bytes
 * @return
 * @throws IOException
 * @throws ProtocolException
 */
private static HttpURLConnection setupConnection(URL url, byte[] bytes) throws IOException, ProtocolException {
    HttpURLConnection conn;
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    return conn;
}