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

@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 .  j  a  va 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()) {
        VolleyLog.e("======4:" + headerName + ";" + map.get(headerName));
        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);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        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:io.mapzone.arena.refine.OrgPersonSplitTableRefineFunction.java

protected Point coordinateForOrganisation(final String organisation, final String plz,
        final String strasseHausNr) throws Exception {
    if (StringUtils.isBlank(plz) || StringUtils.isBlank(strasseHausNr)) {
        return null;
    }/*w  w  w.  j  a  v  a  2 s  .  c o m*/

    final String search1 = "\"lat\":";
    final String search2 = ",\"lng\":";
    final String search3 = "}";
    final String key = "AAdiimU0EwFAoY3G7M7hFx694EdRTuSa";
    final String location = URLEncoder.encode(Joiner.on(", ").join(plz, strasseHausNr), "UTF-8");

    if (locations.containsKey(location)) {
        String coord = locations.getProperty(location);
        String[] coords = coord.split("\\|");
        return GEOMETRYFACTORY
                .createPoint(new Coordinate(Double.parseDouble(coords[0]), Double.parseDouble(coords[1])));
    } else {
        final String url = String.format(
                "http://www.mapquestapi.com/geocoding/v1/address?key=%1$2s&location=%2$2s", key, location);
        final HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("GET");
        con.addRequestProperty("Accept", "application/json");
        con.setDoInput(true);
        con.setDoOutput(true);
        try {
            if (con.getResponseCode() != 200) {
                System.err.println("Keine Koordinate fr " + organisation + ": " + con.getResponseMessage());
            } else {
                final String out = IOUtils.toString(con.getInputStream());
                int index1 = out.indexOf(search1);
                if (index1 > 0) {
                    String out2 = out.substring(index1 + search1.length());
                    int index3 = out2.indexOf(search3);
                    if (index3 > 0) {
                        out2 = out2.substring(0, index3);
                        int index2 = out2.indexOf(search2);
                        if (index2 > 0) {
                            final String latitude = out2.substring(0, index2);
                            final String longitude = out2.substring(index2 + search2.length());
                            Point point = (latitude != null && longitude != null) ? GEOMETRYFACTORY.createPoint(
                                    new Coordinate(Double.parseDouble(longitude), Double.parseDouble(latitude)))
                                    : null;
                            return point;
                        }
                    }
                }
            }
        } finally {
            con.disconnect();
        }
    }
    return null;
}

From source file:com.vimc.ahttp.HurlWorker.java

private void addHeadersIfExists(Request<?> request, HttpURLConnection conn) {
    if (request.getHeaders() != null && request.getHeaders().size() > 0) {
        Map<String, String> map = request.getHeaders();
        for (String headerName : map.keySet()) {
            conn.addRequestProperty(headerName, map.get(headerName));
        }/* w  w  w  .  j a v a  2  s.c  o m*/
    }
}

From source file:sdmx.net.service.wb.WBRESTServiceRegistry.java

private StructureType retrieve(String urlString) throws MalformedURLException, IOException, ParseException {
    Logger.getLogger("sdmx").info("ILORestServiceRegistry: retrieve " + urlString);
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    conn.addRequestProperty("Accept-Encoding", "identity");
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }/*from   w w  w  . jav  a 2  s .  c  om*/
    InputStream in = conn.getInputStream();
    if (SdmxIO.isSaveXml()) {
        String name = System.currentTimeMillis() + ".xml";
        FileOutputStream file = new FileOutputStream(name);
        IOUtils.copy(in, file);
        in = new FileInputStream(name);
    }
    //FileOutputStream temp = new FileOutputStream("temp.xml");
    //org.apache.commons.io.IOUtils.copy(in, temp);
    //temp.close();
    //in.close();
    //in = new FileInputStream("temp.xml");
    ParseParams params = new ParseParams();
    params.setRegistry(this);
    StructureType st = SdmxIO.parseStructure(params, in);
    if (st == null) {
        System.out.println("St is null!");
    } else {
        if (SdmxIO.isSaveXml()) {
            String name = System.currentTimeMillis() + "-21.xml";
            FileOutputStream file = new FileOutputStream(name);
            Sdmx21StructureWriter.write(st, file);
        }
    }
    return st;
}

From source file:org.jumpmind.symmetric.transport.http.HttpTransportManager.java

public IIncomingTransport getPullTransport(Node remote, Node local, String securityToken,
        Map<String, String> requestProperties, String registrationUrl) throws IOException {
    HttpURLConnection conn = createGetConnectionFor(
            new URL(buildURL("pull", remote, local, securityToken, null, registrationUrl)));
    if (requestProperties != null) {
        for (String key : requestProperties.keySet()) {
            conn.addRequestProperty(key, requestProperties.get(key));
        }// w w w  . j a  v a2 s  .com
    }
    return new HttpIncomingTransport(conn, engine.getParameterService());
}

From source file:org.simple.net.httpstacks.HttpUrlConnStack.java

protected void setRequestParams(HttpURLConnection connection, Request<?> request)
        throws ProtocolException, IOException {
    HttpMethod method = request.getHttpMethod();
    connection.setRequestMethod(method.toString());
    // add params
    byte[] body = request.getBody();
    if (body != null) {
        // enable output
        connection.setDoOutput(true);/*from   w ww.j a v  a 2  s  .  c  o  m*/
        // set content type
        connection.addRequestProperty(Request.HEADER_CONTENT_TYPE, request.getBodyContentType());
        // write params data to connection
        DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
        dataOutputStream.write(body);
        dataOutputStream.close();
    }
}

From source file:org.jumpmind.symmetric.transport.http.HttpTransportManager.java

public IIncomingTransport getFilePullTransport(Node remote, Node local, String securityToken,
        Map<String, String> requestProperties, String registrationUrl) throws IOException {
    HttpURLConnection conn = createGetConnectionFor(
            new URL(buildURL("filesync/pull", remote, local, securityToken, null, registrationUrl)));
    if (requestProperties != null) {
        for (String key : requestProperties.keySet()) {
            conn.addRequestProperty(key, requestProperties.get(key));
        }// w w w  . j  a  v  a2 s .  c  o  m
    }
    return new HttpIncomingTransport(conn, engine.getParameterService());
}

From source file:com.example.chengcheng.network.httpstacks.HttpUrlConnStack.java

protected void setRequestParams(HttpURLConnection connection, Request<?> request)
        throws ProtocolException, IOException {
    Request.HttpMethod method = request.getmHttpMethod();
    connection.setRequestMethod(method.toString());
    // add params
    byte[] body = request.getBody();
    if (body != null) {
        // enable output
        connection.setDoOutput(true);// w w  w  .  j  a v  a  2  s .  c o  m
        // set content type
        connection.addRequestProperty(Request.HEADER_CONTENT_TYPE, request.getBodyContentType());
        // write params data to connection
        DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
        dataOutputStream.write(body);
        dataOutputStream.close();
    }
}

From source file:mobac.mapsources.loader.MapPackManager.java

public String downloadMD5SumList() throws IOException, UpdateFailedException {
    String md5eTag = Settings.getInstance().mapSourcesUpdate.etag;
    log.debug("Last md5 eTag: " + md5eTag);
    String updateUrl = System.getProperty("mobac.updateurl");
    if (updateUrl == null)
        throw new RuntimeException("Update url not present");

    byte[] data = null;

    // Proxy p = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved("localhost", 8888));
    HttpURLConnection conn = (HttpURLConnection) new URL(updateUrl).openConnection();
    conn.setInstanceFollowRedirects(false);
    if (md5eTag != null)
        conn.addRequestProperty("If-None-Match", md5eTag);
    int responseCode = conn.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
        log.debug("No newer md5 file available");
        return null;
    }/*from w  w  w  . j av a 2  s.  co m*/
    if (responseCode != HttpURLConnection.HTTP_OK)
        throw new UpdateFailedException(
                "Invalid HTTP response: " + responseCode + " for update url " + conn.getURL());
    // Case HTTP_OK
    InputStream in = conn.getInputStream();
    data = Utilities.getInputBytes(in);
    in.close();
    Settings.getInstance().mapSourcesUpdate.etag = conn.getHeaderField("ETag");
    log.debug("New md5 file retrieved");
    String md5sumList = new String(data);
    return md5sumList;
}

From source file:osmcd.mapsources.loader.MapPackManager.java

public String downloadMD5SumList() throws IOException, UpdateFailedException {
    String md5eTag = Settings.getInstance().mapSourcesUpdate.etag;
    log.debug("Last md5 eTag: " + md5eTag);
    String updateUrl = System.getProperty("osmcd.updateurl");
    if (updateUrl == null)
        throw new RuntimeException("Update url not present");

    byte[] data = null;

    // Proxy p = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved("localhost", 8888));
    HttpURLConnection conn = (HttpURLConnection) new URL(updateUrl).openConnection();
    conn.setInstanceFollowRedirects(false);
    if (md5eTag != null)
        conn.addRequestProperty("If-None-Match", md5eTag);
    int responseCode = conn.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
        log.debug("No newer md5 file available");
        return null;
    }//w  ww .j  a va  2 s .  co  m
    if (responseCode != HttpURLConnection.HTTP_OK)
        throw new UpdateFailedException(
                "Invalid HTTP response: " + responseCode + " for update url " + conn.getURL());
    // Case HTTP_OK
    InputStream in = conn.getInputStream();
    data = Utilities.getInputBytes(in);
    in.close();
    Settings.getInstance().mapSourcesUpdate.etag = conn.getHeaderField("ETag");
    log.debug("New md5 file retrieved");
    String md5sumList = new String(data);
    return md5sumList;
}