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.github.thorqin.webapi.oauth2.OAuthClient.java

public static AccessToken obtainAccessTokenByCode(String authorityServerUri, String clientId,
        String clientSecret, String code, String redirectUri, boolean useBasicAuthentication)
        throws IOException, OAuthException {
    String rawData = makeObtainAccessTokenByCode(clientId, clientSecret, code, redirectUri,
            useBasicAuthentication);/*from w w  w.j a va  2s  .co  m*/
    String type = "application/x-www-form-urlencoded";
    URL u = new URL(authorityServerUri);
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    conn.setDoOutput(true);
    if (useBasicAuthentication) {
        String basicAuthentication = Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes());
        conn.setRequestProperty("Authorization", "Basic " + basicAuthentication);
    }
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", type);
    conn.setRequestProperty("Content-Length", String.valueOf(rawData.length()));
    try (OutputStream os = conn.getOutputStream()) {
        os.write(rawData.getBytes());
    }
    try (InputStream is = conn.getInputStream(); InputStreamReader reader = new InputStreamReader(is)) {
        AccessTokenResponse token = Serializer.fromJson(reader, AccessTokenResponse.class);
        if (token.error != null) {
            throw new OAuthException(token.error, token.errorDescription, token.errorUri);
        }
        return token;
    }
}

From source file:ly.stealth.punxsutawney.Marathon.java

private static JSONObject sendRequest(String uri, String method, JSONObject json) throws IOException {
    URL url = new URL(Marathon.url + uri);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    try {//from  w w  w.  j a v  a 2  s . c o  m
        c.setRequestMethod(method);

        if (method.equalsIgnoreCase("POST")) {
            byte[] body = json.toString().getBytes("utf-8");
            c.setDoOutput(true);
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Content-Length", "" + body.length);
            c.getOutputStream().write(body);
        }

        return (JSONObject) JSONValue.parse(new InputStreamReader(c.getInputStream(), "utf-8"));
    } catch (IOException e) {
        if (c.getResponseCode() == 404 && method.equals("GET"))
            return null;

        ByteArrayOutputStream response = new ByteArrayOutputStream();
        InputStream err = c.getErrorStream();
        if (err == null)
            throw e;

        Util.copyAndClose(err, response);
        IOException ne = new IOException(e.getMessage() + ": " + response.toString("utf-8"));
        ne.setStackTrace(e.getStackTrace());
        throw ne;
    } finally {
        c.disconnect();
    }
}

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

public static String doPOST(String urlstr, List<BasicNameValuePair> params) throws IOException {
    String result = null;//  w  w  w. j a  v  a 2s  .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:com.eyekabob.util.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  ww .j a va  2s.  co m*/
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
// COFFBR01 MODIFIED
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);
    }
    Util.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 value = params.get(key);
            if (value instanceof byte[]) {
                dataparams.putByteArray(key, (byte[]) value);
            }
        }

        // 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:com.thyn.backend.gcm.GcmSender.java

public static String createDeviceGroup(String notification_key_name, String registration_token) {
    String Response_Notification_Key = null;
    try {/*w ww.  j a va 2s .  c om*/
        // 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", "create");
            jGcmData.put("notification_key_name", notification_key_name.trim());
            jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]"));
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }
        Logger.logInfo(jGcmData.toString());

        // 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();
        String resp = IOUtils.toString(inputStream);
        Logger.logInfo("the response from GCM server is: " + resp);
        JSONObject jResp = new JSONObject(resp);
        Response_Notification_Key = jResp.getString("notification_key");

    } catch (IOException e) {
        Logger.logError("Unable to create a device group.", e);

    }
    return Response_Notification_Key;
}

From source file:com.thyn.backend.gcm.GcmSender.java

public static void sendMessageToTopic(String topic, String message) {
    try {/* ww w.ja v  a  2  s.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", message);
        // Where to send GCM message.
        String topicName = "/topics/topic_thyN_" + topic.trim();
        if (topic != null) {
            jGcmData.put("to", topicName);
        } 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("Sending message: '" + message + "' to " + topicName);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (NullPointerException e) {
        e.printStackTrace();
    } 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();
    }
}

From source file:com.enefsy.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.  ja  v a 2 s  .c  om
 * @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);
    }
    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());

        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.thyn.backend.gcm.GcmSender.java

public static String removeDeviceFromDeviceGroup(String notification_key_name, String notification_key,
        String registration_token) {
    String Response_Notification_Key = null;
    try {//from   www  .j  a v a  2s  .  c  o m
        // 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", "remove");
            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();
        Logger.logInfo("the message sent is" + jGcmData.toString());
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        Logger.logInfo("the response from GSM server is: " + resp);
        JSONObject jResp = new JSONObject(resp);
        Response_Notification_Key = jResp.getString("notification_key");

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

    }
    return Response_Notification_Key;
}

From source file:Main.java

public static String customrequest(String url, HashMap<String, String> params, String method) {
    try {/*from   w  ww . j  ava  2 s. c  o  m*/

        URL postUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(5 * 1000);

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");

        conn.connect();
        OutputStream out = conn.getOutputStream();
        StringBuilder sb = new StringBuilder();
        if (null != params) {
            int i = params.size();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (i == 1) {
                    sb.append(entry.getKey() + "=" + entry.getValue());
                } else {
                    sb.append(entry.getKey() + "=" + entry.getValue() + "&");
                }

                i--;
            }
        }
        String content = sb.toString();
        out.write(content.getBytes("UTF-8"));
        out.flush();
        out.close();
        InputStream inStream = conn.getInputStream();
        String result = inputStream2String(inStream);
        conn.disconnect();
        return result;
    } catch (Exception e) {
        // TODO: handle exception
    }
    return null;
}

From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java

/**
 * Opens the connection to Mojang's profile API
 * /*www .  ja v  a 2 s.com*/
 * @since 0.0.1
 * @version 0.0.1
 * 
 * @return The {@link HttpURLConnection} object to the API server
 * @throws IOException If there is a problem opening the stream, a malformed
 *                     URL, or if there is a ProtocolException
 */
private static HttpURLConnection createConnection() throws IOException {
    URL url = new URL(UUIDFetcher.PROFILE_URL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    return connection;
}