Example usage for java.net HttpURLConnection addRequestProperty

List of usage examples for java.net HttpURLConnection addRequestProperty

Introduction

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

Prototype

public void addRequestProperty(String key, String value) 

Source Link

Document

Adds a general request property specified by a key-value pair.

Usage

From source file:com.hackerati.android.user_sdk.volley.HHurlStack.java

private static void addBodyIfExists(final HttpURLConnection connection, final Request<?> request)
        throws IOException, AuthFailureError {
    final byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);/* www .  j  a v a2  s .c  o m*/
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}

From source file:localSPs.SpiderOakAPI.java

public static String connectWithREST(String url, String method)
        throws IOException, ProtocolException, MalformedURLException {
    String newURL = "";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // Connect with a REST Method: GET, DELETE, PUT
    con.setRequestMethod(method);//from   w  w  w .j  a  v  a2 s. com
    //add request header
    con.setReadTimeout(20000);
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    if (method.equals(DELETE) || method.equals(PUT))
        con.addRequestProperty("Authorization", "Base M5XWW5JNONZWUMSANBXXI3LBNFWC4Y3PNU5E2NDSNFXTEMZVJ5QWW");

    int responseCode = con.getResponseCode();
    // Read response
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    newURL = response.toString();
    return newURL;
}

From source file:com.denimgroup.threadfix.service.defects.RestUtils.java

public static InputStream postUrl(String urlString, String data, String username, String password) {
    URL url = null;//from w  w w  . j  a v  a  2  s. c  o m
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        log.warn("URL used for POST was bad: '" + urlString + "'");
        return null;
    }

    HttpURLConnection httpConnection = null;
    OutputStreamWriter outputWriter = null;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();

        setupAuthorization(httpConnection, username, password);

        httpConnection.addRequestProperty("Content-Type", "application/json");
        httpConnection.addRequestProperty("Accept", "application/json");

        httpConnection.setDoOutput(true);
        outputWriter = new OutputStreamWriter(httpConnection.getOutputStream());
        outputWriter.write(data);
        outputWriter.flush();

        InputStream is = httpConnection.getInputStream();

        return is;
    } catch (IOException e) {
        log.warn("IOException encountered trying to post to URL with message: " + e.getMessage());
        if (httpConnection == null) {
            log.warn(
                    "HTTP connection was null so we cannot do further debugging of why the HTTP request failed");
        } else {
            try {
                InputStream errorStream = httpConnection.getErrorStream();
                if (errorStream == null) {
                    log.warn("Error stream from HTTP connection was null");
                } else {
                    log.warn(
                            "Error stream from HTTP connection was not null. Attempting to get response text.");
                    String postErrorResponse = IOUtils.toString(errorStream);
                    log.warn("Error text in response was '" + postErrorResponse + "'");
                }
            } catch (IOException e2) {
                log.warn("IOException encountered trying to read the reason for the previous IOException: "
                        + e2.getMessage(), e2);
            }
        }
    } finally {
        if (outputWriter != null) {
            try {
                outputWriter.close();
            } catch (IOException e) {
                log.warn("Failed to close output stream in postUrl.", e);
            }
        }
    }

    return null;
}

From source file:com.createtank.payments.coinbase.RequestClient.java

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry,
        String accessToken) throws IOException, UnsupportedRequestVerbException {

    if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) {
        throw new UnsupportedRequestVerbException();
    }//from   w  w w  .ja v  a 2  s.  c o m
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request;

        switch (verb) {
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        default:
            throw new RuntimeException("RequestVerb not implemented: " + verb);
        }

        ((HttpEntityEnclosingRequestBase) request)
                .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));

        request.addHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, json, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String url = BASE_URL + method;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());
    conn.addRequestProperty("Content-Type", "application/json");

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(json.toString());
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, json, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

From source file:com.adr.raspberryleds.HTTPUtils.java

public static JSONObject execPOST(String address, JSONObject params) throws IOException {

    BufferedReader readerin = null;
    Writer writerout = null;/*from   w  ww  . jav  a 2  s . c  o  m*/

    try {
        URL url = new URL(address);
        String query = params.toString();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000 /* milliseconds */);
        connection.setConnectTimeout(15000 /* milliseconds */);
        connection.setRequestMethod("POST");
        connection.setAllowUserInteraction(false);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8");
        connection.addRequestProperty("Content-length", String.valueOf(query.length()));

        writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writerout.write(query);
        writerout.flush();

        writerout.close();
        writerout = null;

        int responsecode = connection.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) {
            StringBuilder text = new StringBuilder();

            readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = readerin.readLine()) != null) {
                text.append(line);
                text.append(System.getProperty("line.separator"));
            }

            JSONObject result = new JSONObject(text.toString());

            if (result.has("exception")) {
                throw new IOException(
                        MessageFormat.format("Remote exception: {0}.", result.getString("exception")));
            } else {
                return result;
            }
        } else {
            throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}",
                    Integer.toString(responsecode), connection.getResponseMessage()));
        }
    } catch (JSONException ex) {
        throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage()));
    } finally {
        if (writerout != null) {
            writerout.close();
            writerout = null;
        }
        if (readerin != null) {
            readerin.close();
            readerin = null;
        }
    }
}

From source file:org.apache.niolex.commons.net.HTTPUtil.java

/**
 * Do the HTTP request./*from  w  w  w  .  j a va 2s . c o  m*/
 *
 * @param strUrl the request URL
 * @param params the request parameters
 * @param paramCharset the charset used to send the request parameters
 * @param headers the request headers
 * @param connectTimeout the connection timeout
 * @param readTimeout the data read timeout
 * @param useGet whether do we use the HTTP GET method
 * @return the response pair; a is response header map, b is response body
 * @throws NetException
 */
public static final Pair<Map<String, List<String>>, byte[]> doHTTP(String strUrl, Map<String, String> params,
        String paramCharset, Map<String, String> headers, int connectTimeout, int readTimeout, boolean useGet)
        throws NetException {
    LOG.debug("Start HTTP {} request to [{}], C{}R{}.", useGet ? "GET" : "POST", strUrl, connectTimeout,
            readTimeout);
    InputStream in = null;
    try {
        // 1. For get, we pass parameters in URL; for post, we save it in reqBytes.
        byte[] reqBytes = null;
        if (!CollectionUtil.isEmpty(params)) {
            if (useGet) {
                strUrl = strUrl + '?' + prepareWwwFormUrlEncoded(params, paramCharset);
            } else {
                reqBytes = StringUtil.strToAsciiByte(prepareWwwFormUrlEncoded(params, paramCharset));
            }
        }
        URL url = new URL(strUrl); // We use Java URL to do the HTTP request.
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        // 2. validate to Connection type.
        if (!(ucon instanceof HttpURLConnection)) {
            throw new NetException(NetException.ExCode.INVALID_URL_TYPE,
                    "The request is not in HTTP protocol.");
        }
        final HttpURLConnection httpCon = (HttpURLConnection) ucon;
        // 3. We add all the request headers.
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpCon.addRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        // 4. For get or no parameter, we do not output data; for post, we pass parameters in Body.
        if (reqBytes == null) {
            httpCon.setDoOutput(false);
        } else {
            httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpCon.setRequestProperty("Content-Length", Integer.toString(reqBytes.length));
            httpCon.setRequestMethod("POST");
            httpCon.setDoOutput(true);
        }
        httpCon.setDoInput(true);
        httpCon.connect();
        // 5. do output if needed.
        if (reqBytes != null) {
            StreamUtil.writeAndClose(httpCon.getOutputStream(), reqBytes);
        }
        // 6. Get the input stream.
        in = httpCon.getInputStream();
        final int contentLength = httpCon.getContentLength();
        validateHttpCode(strUrl, httpCon);
        byte[] ret = null;
        // 7. Read response byte array according to the strategy.
        if (contentLength > 0) {
            ret = commonDownload(contentLength, in);
        } else {
            ret = unusualDownload(strUrl, in, MAX_BODY_SIZE, true);
        }
        // 8. Parse the response headers.
        LOG.debug("Succeeded to execute HTTP request to [{}], response size {}.", strUrl, ret.length);
        return Pair.create(httpCon.getHeaderFields(), ret);
    } catch (NetException e) {
        LOG.info(e.getMessage());
        throw e;
    } catch (Exception e) {
        String msg = "Failed to execute HTTP request to [" + strUrl + "], msg=" + e.toString();
        LOG.warn(msg);
        throw new NetException(NetException.ExCode.IOEXCEPTION, msg, e);
    } finally {
        // Close the input stream.
        StreamUtil.closeStream(in);
    }
}

From source file:com.android.volley.toolbox.http.HurlStack.java

/**
 * Add headers and user agent to an {@code }
 *
 * @param connection        The {@linkplain HttpURLConnection} to add request headers to
 * @param userAgent         The User Agent to identify on server
 * @param additionalHeaders The headers to add to the request
 *///from   w w w .  ja va2 s  . c  o  m
private static void addHeadersToConnection(HttpURLConnection connection, String userAgent,
        Map<String, String> additionalHeaders) {

    connection.setRequestProperty(HEADER_USER_AGENT, userAgent);
    for (String headerName : additionalHeaders.keySet()) {
        connection.addRequestProperty(headerName, additionalHeaders.get(headerName));
    }
}

From source file:com.iflytek.android.framework.volley.toolbox.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);//from w  w  w  . ja  v a2s  .co  m
        VolleyLog.e("======3:" + request.getBodyContentType());
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}

From source file:common.net.volley.toolbox.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {

    // before preConnect

    byte[] body = request.getBody();
    if (body != null) {
        stethoManager.preConnect(connection, new ByteArrayRequestEntity(request.getBody()));

        connection.setDoOutput(true);//  w  w  w  .  jav a 2  s . c  o  m
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());

        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();

    }
}

From source file:LNISmokeTest.java

/**
 * Fix basic auth./*from www .j av  a 2 s. c  o  m*/
 * 
 * Set up HTTP basic authentication based on user/password in URL.
 * The HttpURLConnection class should do this itself!
 * 
 * @param url the url
 * @param conn the conn
 */
private static void fixBasicAuth(URL url, HttpURLConnection conn) {
    String userinfo = url.getUserInfo();
    if (userinfo != null) {
        String cui = new String(Base64.encodeBase64(userinfo.getBytes()));
        conn.addRequestProperty("Authorization", "Basic " + cui);
        System.err.println("DEBUG: Sending Basic auth=" + cui);
    }
}