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:gov.nasa.arc.geocam.geocam.HttpPost.java

public static int post(String url, JSONObject json, String username, String password) throws IOException {
    HttpURLConnection conn = createConnection(url, username, password);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "application/json");

    byte[] jsonBytes = json.toString().getBytes("UTF-8");

    conn.setRequestProperty("Content-Length", Integer.toString(jsonBytes.length));

    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.write(jsonBytes);//from   w  w  w  .j a  va  2s .c o m
    out.flush();

    InputStream in = conn.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in), 2048);

    for (String line = reader.readLine(); line != null; line = reader.readLine()) {
    }
    out.close();

    int responseCode = 0;
    responseCode = conn.getResponseCode();
    return responseCode;
}

From source file:Main.java

private static HttpURLConnection initHttpURLConn(String requestURL)
        throws MalformedURLException, IOException, ProtocolException {
    URL url = new URL(requestURL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(TIME_OUT);
    connection.setReadTimeout(TIME_OUT);
    connection.setDoInput(true);//  www. ja va  2s. c  o m
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Charset", CHARSET);
    connection.setRequestProperty("connection", "keep-alive");
    return connection;
}

From source file:org.lightjason.agentspeak.action.buildin.rest.IBaseRest.java

/**
 * creates a HTTP connection and reads the data
 *
 * @param p_url url/*from   w w w .j a va  2  s .  c o m*/
 * @return url data
 * @throws IOException is thrown on connection errors
 */
private static String httpdata(final String p_url) throws IOException {
    final HttpURLConnection l_connection = (HttpURLConnection) new URL(p_url).openConnection();

    // follow HTTP redirects
    l_connection.setInstanceFollowRedirects(true);

    // set a HTTP-User-Agent if not exists
    l_connection.setRequestProperty("User-Agent",
            (System.getProperty("http.agent") == null) || (System.getProperty("http.agent").isEmpty())
                    ? CCommon.PACKAGEROOT + CCommon.configuration().getString("version")
                    : System.getProperty("http.agent"));

    // read stream data
    final InputStream l_stream = l_connection.getInputStream();
    final String l_return = CharStreams.toString(new InputStreamReader(l_stream,
            (l_connection.getContentEncoding() == null) || (l_connection.getContentEncoding().isEmpty())
                    ? Charsets.UTF_8
                    : Charset.forName(l_connection.getContentEncoding())));
    Closeables.closeQuietly(l_stream);

    return l_return;
}

From source file:core.Utility.java

private static ArrayList<String> getSynonymsWiktionary(String _word) throws MalformedURLException, IOException {
    ArrayList<String> _list = new ArrayList();
    try {//from w w w. j a v a2  s. co  m

        URL url = new URL("http://www.igrec.ca/project-files/wikparser/wikparser.php?word=" + _word
                + "&query=syn&lang=en");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        while ((output = br.readLine()) != null) {
            boolean isEmpty = output.contains("No listed synonyms.")
                    || output.contains("ERROR: The Wiktionary API did not return a page for that word.");

            if (isEmpty) {
                conn.disconnect();
                return _list;
            } else {
                String[] arr = output.trim().split(" ");
                for (String s : arr) {
                    if (s.length() > 2) {
                        _list.add(s);
                    }
                }
            }
        }

        conn.disconnect();

    } catch (MalformedURLException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
    return _list;
}

From source file:com.uniteddev.Unity.Downloader.java

public static HttpURLConnection setupHTTP(String fileurl) throws MalformedURLException, IOException {
    HttpURLConnection httpConnection = (HttpURLConnection) new URL(fileurl).openConnection();
    httpConnection.setRequestMethod("GET");
    httpConnection.setRequestProperty("Content-Type", "application/java-archive");
    httpConnection.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31");
    return httpConnection;
}

From source file:io.github.bonigarcia.wdm.Downloader.java

private static HttpURLConnection getConnection(URL url) throws IOException {
    Proxy proxy = createProxy();//from   w w  w . j av a 2  s .  c o m
    URLConnection conn1 = proxy != null ? url.openConnection(proxy) : url.openConnection();
    HttpURLConnection conn = (HttpURLConnection) conn1;
    conn.setRequestProperty("User-Agent", "Mozilla/5.0");
    conn.addRequestProperty("Connection", "keep-alive");
    conn.setInstanceFollowRedirects(true);
    HttpURLConnection.setFollowRedirects(true);
    conn.connect();
    return conn;
}

From source file:org.openbmap.soapclient.CheckServerTask.java

/**
 * Checks connection to openbmap.org/*  www  . j  a v a2  s  .c  om*/
 * @return true on successful http connection
 */
private static boolean isOnline() {
    try {
        Log.v(TAG, "Ping " + Preferences.VERSION_CHECK_URL);
        final URL url = new URL(Preferences.VERSION_CHECK_URL);
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Connection", "close");
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.connect();
        if (connection.getResponseCode() == 200) {
            Log.i(TAG, String.format("Good: Server reply %s - device & server online",
                    connection.getResponseCode()));
            return true;
        } else {
            Log.w(TAG, String.format("Bad: Http ping failed (server reply %s).", connection.getResponseCode()));
        }
    } catch (final IOException e) {
        Log.w(TAG, "Bad: Http ping failed (no response)..");
    }
    return false;
}

From source file:com.jiramot.foursquare.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//from  www. j  a  va2  s.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;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Foursquare-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FoursquareAndroidSDK");
    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:com.example.admin.processingboilerplate.JsonIO.java

public static JSONObject pushJson(String requestURL, String jsonDataName, JSONObject json) {
    try {//from   ww  w.j a  v a2 s .co  m
        String boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        //HttpURLConnection con = (HttpURLConnection) url.openConnection();
        URLConnection uc = (url).openConnection();
        HttpURLConnection con = requestURL.startsWith("https") ? (HttpsURLConnection) uc
                : (HttpURLConnection) uc;
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        con.setRequestProperty("User-Agent", USER_AGENT);
        OutputStream outputStream = con.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);

        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"" + "data" + "\"").append(CRLF);
        writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
        writer.append(CRLF);
        writer.append(json.toString()).append(CRLF);
        writer.flush();

        writer.append(CRLF).flush();
        writer.append("--" + boundary + "--").append(CRLF);
        writer.close();
        int status = con.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            StringBuilder sb = load(con);
            try {
                json = new JSONObject(sb.toString());
                return json;
            } catch (JSONException e) {
                Log.e("loadJson", e.getMessage(), e);
                e.printStackTrace();
                return new JSONObject();
            }
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new JSONObject();
}

From source file:br.com.ufc.palestrasufc.twitter.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from  w  w w . ja  v  a 2s  .c  o m*/
 * 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("Twitter-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " TwitterAndroidSDK");
    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;
}