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.iflytek.android.framework.volley.toolbox.HurlStack.java

@SuppressWarnings("deprecation")
/* package */static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    VolleyLog.e("======setConnectionParametersForRequest:");
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards
        // compatibility.
        // If the request's post body is null, then the assumption is that
        // the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length
            // explicitly,
            // since this is handled by HttpURLConnection using the size of
            // the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);//from   w  ww  .java 2 s . com
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection
        // defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:

        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:com.zlk.bigdemo.android.volley.toolbox.HurlStack.java

private HttpResponse performNormalREquest(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 v a  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:neal.http.impl.httpstack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, HttpErrorCollection.AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//  w ww  .  j a v  a  2  s .  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);
    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.autonavi.gxdtaojin.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());/*  w w w.  j a  v  a  2  s . 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 = null;
    try {
        parsedUrl = new URL(url);
    } catch (Throwable t) {
        t.printStackTrace();
        parsedUrl = new URL("http://www.google.com");
    }
    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.mome.main.netframe.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());/*  w ww .ja v  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);
    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.adaptris.core.http.client.net.MetadataRequestHeaders.java

@Override
public HttpURLConnection addHeaders(AdaptrisMessage msg, HttpURLConnection target) {
    MetadataCollection metadataSubset = getFilter().filter(msg);
    for (MetadataElement me : metadataSubset) {
        String value = unfold(me.getValue());
        log.trace("Adding Request Property [{}: {}]", me.getKey(), value);
        target.addRequestProperty(me.getKey(), value);
    }/*from w  w  w. j  av  a2s .  c  om*/
    return target;
}

From source file:com.farru.android.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 w w  w.j a v  a2  s .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);

    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.daidiansha.acarry.control.network.core.volley.toolbox.HurlStack.java

@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards
        // compatibility.
        // If the request's post body is null, then the assumption is that
        // the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length
            // explicitly,
            // since this is handled by HttpURLConnection using the size of
            // the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);/*from w  w  w.java  2  s. c o m*/
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection
        // defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        // connection.setRequestMethod("PATCH");
        // If server doesnt support patch uncomment this
        connection.setRequestMethod("POST");
        connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:com.chen.cy.talkimage.network.xvolley.XHurlStack.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   www. ja v a 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 = 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) {
            //
            // ?????
            for (int i = 0; i < header.getValue().size(); i++) {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(i));
                response.addHeader(h);
            }
        }
    }
    return response;
}

From source file:org.graylog2.alarmcallbacks.hipchat.HipChatTrigger.java

public void trigger(AlertCondition condition, AlertCondition.CheckResult alert) throws AlarmCallbackException {
    final URL url;
    try {/*from w w w  . jav  a 2 s  . c o m*/
        if (Strings.isNullOrEmpty(apiURL)) {
            url = new URL(
                    "https://api.hipchat.com/v2/room/" + URLEncoder.encode(room, "UTF-8") + "/notification");
        } else {
            url = new URL(apiURL + "/v2/room/" + URLEncoder.encode(room, "UTF-8") + "/notification");
        }
    } catch (MalformedURLException | UnsupportedEncodingException e) {
        throw new AlarmCallbackException("Error while constructing URL of HipChat API.", e);
    }

    final HttpURLConnection conn;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Authorization", "Bearer " + apiToken);
        conn.addRequestProperty("Content-Type", "application/json");
    } catch (IOException e) {
        throw new AlarmCallbackException("Could not open connection to HipChat API", e);
    }

    try (final OutputStream outputStream = conn.getOutputStream()) {
        outputStream.write(objectMapper.writeValueAsBytes(buildRoomNotification(condition, alert)));
        outputStream.flush();

        if (conn.getResponseCode() != 204) {
            throw new AlarmCallbackException("Unexpected HTTP response status " + conn.getResponseCode());
        }
    } catch (IOException e) {
        throw new AlarmCallbackException("Could not POST event trigger to HipChat API", e);
    }
}