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:crow.util.Util.java

public static String urlPost(HttpURLConnection conn, String encodePostParam) throws IOException {
    int responseCode = -1;
    OutputStream osw = null;/*from   w w  w  . ja  va2 s.com*/
    try {
        conn.setConnectTimeout(20000);
        conn.setReadTimeout(12000);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        byte[] bytes = encodePostParam.getBytes("UTF-8");
        conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));
        osw = conn.getOutputStream();
        osw.write(bytes);
        osw.flush();
        responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("");
        } else {
            String s = inputStreamToString(conn.getInputStream());
            return s;
        }
    } finally {
        try {
            if (osw != null)
                osw.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:disko.DU.java

public static String request(String targetUrl, String method, String text, String contentType)
        throws Exception {
    URL url = new URL(targetUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (method != null)
        conn.setRequestMethod(method);/*  w  w w.j a  va 2 s . com*/

    if (contentType != null)
        conn.setRequestProperty("Content-Type", contentType);

    if (text != null) {
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.getOutputStream().write(text.getBytes());
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(text.getBytes());
        out.flush();
        out.close();
    }

    if (conn.getResponseCode() != 200)
        throw new RuntimeException("HTTPClient failed: " + conn.getResponseCode());

    StringBuffer responseBuffer = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    String eol = new String(new byte[] { 13 });
    while ((line = in.readLine()) != null) {
        responseBuffer.append(line);
        responseBuffer.append(eol);
    }
    in.close();

    return responseBuffer.toString();
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String net(String strUrl, Map<String, Object> params, String method) throws Exception {
    HttpURLConnection conn = null;
    BufferedReader reader = null;
    String rs = null;//from www .jav a2s  .c o  m
    try {
        StringBuffer sb = new StringBuffer();
        if (method == null || method.equals("GET")) {
            strUrl = strUrl + "?" + urlencode(params);
        }
        URL url = new URL(strUrl);
        conn = (HttpURLConnection) url.openConnection();
        if (method == null || method.equals("GET")) {
            conn.setRequestMethod("GET");
        } else {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
        }
        conn.setRequestProperty("User-agent", userAgent);
        conn.setUseCaches(false);
        conn.setConnectTimeout(DEF_CONN_TIMEOUT);
        conn.setReadTimeout(DEF_READ_TIMEOUT);
        conn.setInstanceFollowRedirects(false);
        conn.connect();
        if (params != null && method.equals("POST")) {
            try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
                out.writeBytes(urlencode(params));
            }
        }
        InputStream is = conn.getInputStream();
        reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sb.append(strRead);
        }
        rs = sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
    return rs;
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * @param file - file on the repo//from ww w  . j ava 2s . c  o m
 * @return boolean representing if the file exists 
 */
public static boolean fileExists(String file) {
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(Locations.masterRepo + "/FTB2/" + file)
                .openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        connection.setRequestMethod("HEAD");
        return (connection.getResponseCode() == 200);
    } catch (Exception e) {
        return false;
    }
}

From source file:com.facebook.android.FBUtil.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  ava  2s  .com*/
 * @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-FBUtil", 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:de.minestar.minestarlibrary.utils.PlayerUtils.java

private static String sendHTTPGetRequest(String URL) {
    try {//from www.j a v  a  2s.  c o m
        URL urlObject = new URL(URL);
        HttpURLConnection httpConnection = (HttpURLConnection) urlObject.openConnection();

        // optional default is GET
        httpConnection.setRequestMethod("GET");

        // add request header
        httpConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
        int responseCode = httpConnection.getResponseCode();

        // the responseCode must be 200, otherwise the answer is incorrect
        // (i.e. 204 for noContent)
        if (responseCode == 200) {
            BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

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

            // return response as String
            return response.toString();
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.chiorichan.util.WebUtils.java

/**
 * Establishes an HttpURLConnection from a URL, with the correct configuration to receive content from the given URL.
 * /*from   ww w  .  j ava 2s.  co m*/
 * @param url
 *            The URL to set up and receive content from
 * @return A valid HttpURLConnection
 * 
 * @throws IOException
 *             The openConnection() method throws an IOException and the calling method is responsible for handling it.
 */
public static HttpURLConnection openHttpConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(false);
    System.setProperty("http.agent", getUserAgent());
    conn.setRequestProperty("User-Agent", getUserAgent());
    HttpURLConnection.setFollowRedirects(true);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    return conn;
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * @param file - the name of the file, as saved to the repo (including extension)
 * @return - the direct link/*from   w w  w .ja  v  a 2  s .co m*/
 */
public static String getStaticCreeperhostLink(String file) {
    String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer()))
            ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer())
            : Locations.masterRepo;
    resolved += "/FTB2/static/" + file;
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) new URL(resolved).openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        connection.setRequestMethod("HEAD");
        if (connection.getResponseCode() != 200) {
            for (String server : downloadServers.values()) {
                if (connection.getResponseCode() != 200) {
                    resolved = "http://" + server + "/FTB2/static/" + file;
                    connection = (HttpURLConnection) new URL(resolved).openConnection();
                    connection.setRequestProperty("Cache-Control", "no-transform");
                    connection.setRequestMethod("HEAD");
                } else {
                    break;
                }
            }
        }
    } catch (IOException e) {
    }
    connection.disconnect();
    return resolved;
}

From source file:eu.crowdrec.contest.sender.RequestSender.java

/**
 * Send a line from a logFile to an HTTP server (single-threaded).
 * /*from w w  w  .j  a  va2  s .  com*/
 * @param logline the line that should by sent
 * 
 * @param connection the connection to the http server, must not be null
 * 
 * @return the response or null (if an error has been detected)
 */
static private String excutePost(final String logline, final String serverURL) {

    // split the logLine into several token
    String[] token = logline.split("\t");

    String type = token[0];
    String property = token[3];
    String entity = token[4];

    // encode the content as URL parameters.
    String urlParameters = "";
    try {
        urlParameters = String.format("type=%s&properties=%s&entities=%s", URLEncoder.encode(type, "UTF-8"),
                URLEncoder.encode(property, "UTF-8"), URLEncoder.encode(entity, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        logger.warn(e1.toString());
    }

    // initialize a HTTP connection to the server
    // reuse of connection objects is delegated to the JVM
    HttpURLConnection connection = null;

    try {
        final URL url = new URL(serverURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        // Get Response
        BufferedReader rd = null;
        InputStream is = null;
        try {
            is = connection.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is));

            StringBuffer response = new StringBuffer();
            for (String line = rd.readLine(); line != null; line = rd.readLine()) {
                response.append(line);
                response.append(" ");
            }
            return response.toString();
        } catch (IOException e) {
            logger.warn("receivind response failed, ignored.");
        } finally {
            if (is != null) {
                is.close();
            }
            if (rd != null) {
                rd.close();
            }
        }
    } catch (MalformedURLException e) {
        System.err.println("invalid server URL, program stopped.");
        System.exit(-1);
    } catch (IOException e) {
        System.err.println("i/o error connecting the http server, program stopped. e=" + e);
        System.exit(-1);
    } catch (Exception e) {
        System.err.println("general error connecting the http server, program stopped. e:" + e);
        e.printStackTrace();
        System.exit(-1);
    } finally {
        // close the connection
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * @param file - the name of the file, as saved to the repo (including extension)
 * @return - the direct link//from   w ww.j  a  v  a2 s .co  m
 */
public static String getCreeperhostLink(String file) {
    String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer()))
            ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer())
            : Locations.masterRepo;
    resolved += "/FTB2/" + file;
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) new URL(resolved).openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        connection.setRequestMethod("HEAD");
        for (String server : downloadServers.values()) {
            if (connection.getResponseCode() != 200) {
                if (!server.contains("creeper")) {
                    file = file.replaceAll("%5E", "/");
                }

                resolved = "http://" + server + "/FTB2/" + file;
                connection = (HttpURLConnection) new URL(resolved).openConnection();
                connection.setRequestProperty("Cache-Control", "no-transform");
                connection.setRequestMethod("HEAD");
            } else {
                break;
            }
        }
    } catch (IOException e) {
    }
    connection.disconnect();
    return resolved;
}