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.nxt.zyl.data.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    // chenbo add gzip support,new user-agent
    if (request.isShouldGzip()) {
        map.put(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
    }//from  ww w. j av  a2  s  .  co  m
    map.put(USER_AGENT, mUserAgent);
    // end
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));

    }

    //        if (request instanceof MultiPartRequest) {
    //            setConnectionParametersForMultipartRequest(connection, request);
    //        } else {
    //        }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    if (ENCODING_GZIP.equalsIgnoreCase(connection.getContentEncoding())) {
        response.setEntity(new InflatingEntity(response.getEntity()));
    }
    return response;
}

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

@Override
public HttpResponse performRequest(final Request<?> request, final Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    final HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//w ww .j  a va2  s  .c  o  m
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        final String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    final URL parsedUrl = new URL(url);
    final HttpURLConnection connection = openConnection(parsedUrl, request);
    for (final String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    final ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode;
    try {
        // Will throw IOException if server responds with 401.
        responseCode = connection.getResponseCode();
    } catch (final IOException e) {
        // Will return 401, because now connection has the correct internal
        // state.
        responseCode = connection.getResponseCode();
    }
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could
        // not be retrieved.
        // Signal to the caller that something was wrong with the
        // connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    final StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    final BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (final Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            final Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:com.baseproject.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from   ww w.  j av  a  2  s.co  m
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException(Util.buildHttpErrorMsg("failed", -1, "URL blocked by rewriter: " + url));
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    // if (responseCode == -1) {
    // // -1 is returned by getResponseCode() if the response code could not be retrieved.
    // // Signal to the caller that something was wrong with the connection.
    // throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    // }
    if (responseCode != HttpStatus.SC_NOT_MODIFIED && responseCode != HttpURLConnection.HTTP_OK) {
        InputStream in = null;
        try {
            in = connection.getErrorStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (in == null) {
            throw new IOException(Util.buildHttpErrorMsg("failed", responseCode, "unknown"));
        } else {
            throw new IOException(Util.convertStreamToString(in));
        }
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            if (header.getKey().equals("Set-Cookie")) {
                List<String> cookieValue = header.getValue();
                for (String c : cookieValue) {
                    Header h = new BasicHeader(header.getKey(), c);
                    response.addHeader(h);
                }
            } else {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                response.addHeader(h);
            }
        }
    }
    return response;
}

From source file:com.playbasis.android.playbasissdk.http.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from w  w w .  j a va  2 s.  c  om
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) parsedUrl.openConnection();//openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:edu.asu.msse.dssoni.moviedescrpitionapp.JsonRPCClientViaThread.java

private String post(URL url, Map<String, String> headers, String data) throws Exception {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            connection.addRequestProperty(entry.getKey(), entry.getValue());
        }/*from  www  . j av a 2s. c  om*/
    }
    connection.addRequestProperty("Accept-Encoding", "gzip");
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.connect();
    OutputStream out = null;
    try {
        out = connection.getOutputStream();
        out.write(data.getBytes());
        out.flush();
        out.close();
        int statusCode = connection.getResponseCode();
        if (statusCode != HttpURLConnection.HTTP_OK) {
            throw new Exception("Unexpected status from post: " + statusCode);
        }
    } finally {
        if (out != null) {
            out.close();
        }
    }
    String responseEncoding = connection.getHeaderField("Content-Encoding");
    responseEncoding = (responseEncoding == null ? "" : responseEncoding.trim());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    InputStream in = connection.getInputStream();
    try {
        in = connection.getInputStream();
        if ("gzip".equalsIgnoreCase(responseEncoding)) {
            in = new GZIPInputStream(in);
        }
        in = new BufferedInputStream(in);
        byte[] buff = new byte[1024];
        int n;
        while ((n = in.read(buff)) > 0) {
            bos.write(buff, 0, n);
        }
        bos.flush();
        bos.close();
    } finally {
        if (in != null) {
            in.close();
        }
    }
    android.util.Log.d(this.getClass().getSimpleName(),
            "json rpc request via http returned string " + bos.toString());
    return bos.toString();
}

From source file:com.mars.framework.volley.net.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());// w w w. j  av a 2s  . c  o m
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    connection.setChunkedStreamingMode(0);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:com.kubeiwu.commontool.khttp.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//
    map.putAll(additionalHeaders);/*from  w ww.j a v a 2 s.co m*/
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);// ?url
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);

    for (String headerName : map.keySet()) {// header
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could
        // not be retrieved.
        // Signal to the caller that something was wrong with the
        // connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            // Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            // response.addHeader(h);
            //cookie?
            String key = header.getKey();
            List<String> values = header.getValue();
            if (key.equalsIgnoreCase("set-cookie")) {
                StringBuilder cookieString = new StringBuilder();
                for (String value : values) {
                    cookieString.append(value).append("\n");// \ncookie??
                }
                cookieString.deleteCharAt(cookieString.length() - 1);
                Header h = new BasicHeader(header.getKey(), cookieString.toString());
                response.addHeader(h);
            } else {
                Header h = new BasicHeader(header.getKey(), values.get(0));
                response.addHeader(h);
            }
        }
    }
    System.out.println("performRequest---999999-getStatusLine=" + response.getStatusLine());
    return response;
}

From source file:org.bsc.maven.plugin.confluence.SwizzleApp.java

/**
 * //from ww w .  ja va2  s  .  com
 * @throws Exception 
 */
private void usingHttp() throws Exception {

    Confluence.ProxyInfo proxyInfo = null;

    Confluence confluence = confluence = ConfluenceFactory.createInstanceDetectingVersion(
            url.concat("/rpc/xmlrpc"), //args[0], 
            proxyInfo, username, //args[1], 
            password); //args[2]);

    Page page = confluence.getPage("CIRC", "Best Movies");

    java.io.InputStream is = null;
    java.io.FileOutputStream fos = null;
    try {
        final String req = String.format("%s/%s?pageId=%s", url, ExportFormat.PDF.url, page.getId());
        System.out.println(req);
        java.net.URL _url = new java.net.URL(req);

        HttpURLConnection urlConnection = (HttpURLConnection) _url.openConnection();
        //HttpURLConnection.setFollowRedirects(true);
        //urlConnection.setInstanceFollowRedirects(true);
        String userpass = username + ":" + password;

        String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        urlConnection.addRequestProperty("Authorization", basicAuth);
        urlConnection.addRequestProperty("X-Atlassian-Token", "no-check");
        urlConnection.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");

        urlConnection.setUseCaches(false);

        is = urlConnection.getInputStream();

        fos = new java.io.FileOutputStream("target/out.pdf");

        IOUtils.copy(is, fos);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.navercorp.volleyextensions.volleyer.multipart.stack.MultipartHurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from   w  w w  .j  a va 2s. co  m
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }

    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:com.gitblit.auth.RedmineAuthProvider.java

private String getCurrentUserAsJson(String username, char[] password) throws IOException {
    if (testingJson != null) { // for testing
        return testingJson;
    }/*from w  w w.  j  a va2s  .  c  o  m*/

    String url = this.settings.getString(Keys.realm.redmine.url, "");
    if (!url.endsWith("/")) {
        url = url.concat("/");
    }
    String apiUrl = url + "users/current.json";

    HttpURLConnection http;
    if (username == null) {
        // apikey authentication
        String apiKey = String.valueOf(password);
        http = (HttpURLConnection) ConnectionUtils.openConnection(apiUrl, null, null);
        http.addRequestProperty("X-Redmine-API-Key", apiKey);
    } else {
        // username/password BASIC authentication
        http = (HttpURLConnection) ConnectionUtils.openConnection(apiUrl, username, password);
    }
    http.setRequestMethod("GET");
    http.connect();
    InputStreamReader reader = new InputStreamReader(http.getInputStream());
    return IOUtils.toString(reader);
}