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.xjb.volley.toobox.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.  jav  a  2  s.  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()) {
        try {
            connection.addRequestProperty(headerName, map.get(headerName));
        } catch (Exception e) {

        }
    }
    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) {
            synchronized (HurlStack.class) {
                if (header.getKey().equals("Set-Cookie")) {
                    String cookie = "";
                    List<String> list = header.getValue();
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).contains("IHOME_FRONT_SID")) {
                                String[] ss = list.get(i).split(";");
                                cookie = ss[0];
                            }
                        }
                    }
                    Header h = new BasicHeader(header.getKey(), cookie);
                    response.addHeader(h);
                } else {

                    Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                    response.addHeader(h);

                }

            }

        }
    }
    return response;
}

From source file:com.framework.testcase.testrail.APIClient.java

private Object sendRequest(String method, String uri, Object data) throws MalformedURLException, IOException {
    URL url = new URL(this.m_url + uri);

    // Create the connection object and set the required HTTP method
    // (GET/POST) and headers (content type and basic auth).
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Content-Type", "application/json");

    String auth = getAuthorization(this.m_user, this.m_password);
    conn.addRequestProperty("Authorization", "Basic " + auth);

    if (method.equalsIgnoreCase("POST")) {
        // Add the POST arguments, if any. We just serialize the passed
        // data object (i.e. a dictionary) and then add it to the
        // request body.
        if (data != null) {
            byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8");

            conn.setDoOutput(true);//  www  . j  av  a 2  s  .  c  o m
            OutputStream ostream = conn.getOutputStream();
            ostream.write(block);
            ostream.flush();
        }
    }

    // Execute the actual web request (if it wasn't already initiated
    // by getOutputStream above) and record any occurred errors (we use
    // the error stream in this case).
    int status = 0;
    try {
        status = conn.getResponseCode();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        System.err.println("the request is timeout from the server ,we quite the test");

    } catch (SSLHandshakeException ex) {
        ex.printStackTrace();
        System.err.println("the request is  Remote host closed connection during handshake");
    }

    InputStream istream;
    if (status != 200) {
        istream = conn.getErrorStream();
        if (istream == null) {

            new Exception("TestRail API return HTTP " + status + " (No additional error message received)");

        }
    } else {
        istream = conn.getInputStream();
    }

    // Read the response body, if any, and deserialize it from JSON.
    String text = "";
    if (istream != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8"));

        String line;
        while ((line = reader.readLine()) != null) {
            text += line;
            text += System.getProperty("line.separator");
        }

        reader.close();
    }

    Object result;
    if (text != "") {
        result = JSONValue.parse(text);
    } else {
        result = new JSONObject();
    }

    // Check for any occurred errors and add additional details to
    // the exception message, if any (e.g. the error message returned
    // by TestRail).
    if (status != 200) {
        String error = "No additional error message received";
        if (result != null && result instanceof JSONObject) {
            JSONObject obj = (JSONObject) result;
            if (obj.containsKey("error")) {
                error = '"' + (String) obj.get("error") + '"';
            }
        }

        new Exception("TestRail API returned HTTP " + status + "(" + error + ")");
    }

    return result;
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Create a new Http connection for an URI.
 *//*from w ww. j a v a2 s  .c om*/
public static HttpURLConnection newRequest(Context context, String uri, Set<String> cookies)
        throws IOException {
    if (DEBUG) {
        Log.d(TAG, "Setup connection to " + uri);
    }

    final HttpURLConnection conn = (HttpURLConnection) new URL(uri).openConnection();
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(false);
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(60000);
    conn.setRequestProperty("Accept-Encoding", "gzip");
    conn.setRequestProperty("User-Agent", getUserAgent(context));
    conn.setRequestProperty("Cache-Control", "max-age=0");
    conn.setDoInput(true);

    // Close the connection when the request is done, or the application may
    // freeze due to a bug in some Android versions.
    conn.setRequestProperty("Connection", "close");

    if (conn instanceof HttpsURLConnection) {
        setupSecureConnection(context, (HttpsURLConnection) conn);
    }

    if (cookies != null && !cookies.isEmpty()) {
        final StringBuilder buf = new StringBuilder(256);
        for (final String cookie : cookies) {
            if (buf.length() != 0) {
                buf.append("; ");
            }
            buf.append(cookie);
        }
        conn.addRequestProperty("Cookie", buf.toString());
    }

    return conn;
}

From source file:org.openmrs.module.odkconnector.serialization.web.PatientWebConnectorTest.java

@Test
public void serialize_shouldDisplayAllPatientInformation() throws Exception {

    // compose url
    URL u = new URL(SERVER_URL + "/module/odkconnector/download/patients.form");

    // setup http url connection
    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
    connection.setDoOutput(true);//from   ww w .j  a  v  a2s .c o m
    connection.setRequestMethod("POST");
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);
    connection.addRequestProperty("Content-type", "application/octet-stream");

    // write auth details to connection
    DataOutputStream outputStream = new DataOutputStream(new GZIPOutputStream(connection.getOutputStream()));
    outputStream.writeUTF("admin");
    outputStream.writeUTF("test");
    outputStream.writeBoolean(true);
    outputStream.writeInt(2);
    outputStream.writeInt(1);
    outputStream.close();

    DataInputStream inputStream = new DataInputStream(new GZIPInputStream(connection.getInputStream()));
    Integer responseStatus = inputStream.readInt();

    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

    int count = 0;
    byte[] buffer = new byte[1024];
    while ((count = inputStream.read(buffer)) > 0) {
        arrayOutputStream.write(buffer, 0, count);
    }
    arrayOutputStream.close();
    inputStream.close();

    File file = new File("/home/nribeka/connector.data");
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(arrayOutputStream.toByteArray());
    fos.close();

    inputStream = new DataInputStream(new FileInputStream(file));

    if (responseStatus == HttpURLConnection.HTTP_OK) {

        // total number of patients
        Integer patientCounter = inputStream.readInt();
        System.out.println("Patient Counter: " + patientCounter);
        for (int j = 0; j < patientCounter; j++) {
            System.out.println("=================Patient=====================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Family Name: " + inputStream.readUTF());
            System.out.println("Middle Name: " + inputStream.readUTF());
            System.out.println("Last Name: " + inputStream.readUTF());
            System.out.println("Gender: " + inputStream.readUTF());
            System.out.println("Birth Date: " + inputStream.readUTF());
            System.out.println("Identifier: " + inputStream.readUTF());
            System.out.println("Patients: " + j + " out of " + patientCounter);
        }

        Integer obsCounter = inputStream.readInt();
        System.out.println("Observation Counter: " + obsCounter);
        for (int j = 0; j < obsCounter; j++) {
            System.out.println("==================Observation=================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Concept Name: " + inputStream.readUTF());

            byte type = inputStream.readByte();
            if (type == ObsSerializer.TYPE_STRING)
                System.out.println("Value: " + inputStream.readUTF());
            else if (type == ObsSerializer.TYPE_INT)
                System.out.println("Value: " + inputStream.readInt());
            else if (type == ObsSerializer.TYPE_DOUBLE)
                System.out.println("Value: " + inputStream.readDouble());
            else if (type == ObsSerializer.TYPE_DATE)
                System.out.println("Value: " + inputStream.readUTF());
            System.out.println("Time: " + inputStream.readUTF());
            System.out.println("Obs: " + j + " out of: " + obsCounter);
        }
        Integer formCounter = inputStream.readInt();
        System.out.println("Form Counter: " + formCounter);
        for (int j = 0; j < formCounter; j++) {
            System.out.println("==================Observation=================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Concept Name: " + inputStream.readUTF());

            byte type = inputStream.readByte();
            if (type == ObsSerializer.TYPE_STRING)
                System.out.println("Value: " + inputStream.readUTF());
            else if (type == ObsSerializer.TYPE_INT)
                System.out.println("Value: " + inputStream.readInt());
            else if (type == ObsSerializer.TYPE_DOUBLE)
                System.out.println("Value: " + inputStream.readDouble());
            else if (type == ObsSerializer.TYPE_DATE)
                System.out.println("Value: " + inputStream.readUTF());
            System.out.println("Time: " + inputStream.readUTF());
            System.out.println("Form: " + j + " out of: " + formCounter);
        }
    }
    inputStream.close();
}

From source file:com.twotoasters.android.hoot.HootTransportHttpUrlConnection.java

private void setRequestHeaders(HootRequest request, HttpURLConnection connection) {
    if (request.getHeaders() != null) {
        Iterator<Object> iter = request.getHeaders().keySet().iterator();
        while (iter.hasNext()) {
            String name = (String) iter.next();
            connection.addRequestProperty(name, request.getHeaders().getProperty(name));
        }/*from w w w .j  ava 2  s.  c o  m*/
    }

    if (request.getHoot().isBasicAuth()) {
        connection.addRequestProperty("Authorization", request.getHoot().calculateBasicAuthHeader());
    }
}

From source file:org.apache.qpid.systest.rest.SaslRestTest.java

private void applyCookiesToConnection(List<String> cookies, HttpURLConnection connection) {
    for (String cookie : cookies) {
        connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
    }/*from w  w  w.j a va 2 s  . co m*/
}

From source file:org.dllearner.kb.sparql.TreeBasedConciseBoundedDescriptionGenerator.java

private Model constructWithReplacement(SparqlEndpoint endpoint, String query) throws Exception {
    QueryEngineHTTP qe = new QueryEngineHTTP(endpoint.getURL().toString(), query);
    qe.setDefaultGraphURIs(endpoint.getDefaultGraphURIs());
    String request = qe.toString().replace("GET ", "");

    URL url = new URL(request);
    java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.addRequestProperty(HttpNames.hAccept, WebContent.contentTypeRDFXML);
    try (BufferedReader rdr = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
        Model model = ModelFactory.createDefaultModel();
        String buf = null;//from w w  w .j a va2s .c  o  m
        StringBuilder doc = new StringBuilder();
        while ((buf = rdr.readLine()) != null) {
            // Apply regex on buf
            if (buf.contains("&#")) {
                buf = buf.replace("&#", "");
            }
            // build output
            doc.append(buf);
        }
        try (InputStream is = new ByteArrayInputStream(doc.toString().getBytes(StandardCharsets.UTF_8))) {
            model.read(is, null);
        }
        return model;
    }
}

From source file:de.kp.ames.web.function.access.wms.WmsConsumer.java

/**
 * Issues a request to the server and returns that 
 * server's response. It asks the server to send the 
 * response gzipped to provide a faster transfer time.
 * /*from   w w  w. j a  va 2 s.c  o  m*/
 * @param request
 * @return
 * @throws IOException
 * @throws ServiceException
 */
public Response sendRequest(Request request) throws IOException, ServiceException {

    // retrieve server url
    URL finalURL = request.getFinalURL();

    HttpURLConnection connection = (HttpURLConnection) finalURL.openConnection();
    connection.addRequestProperty("Accept-Encoding", "gzip");

    connection.setRequestMethod("GET");
    InputStream is = connection.getInputStream();

    if (connection.getContentEncoding() != null && connection.getContentEncoding().indexOf("gzip") != -1) {
        is = new GZIPInputStream(is);
    }

    String contentType = connection.getContentType();
    return request.createResponse(contentType, is);

}

From source file:com.nexmo.sdk.core.client.Client.java

/**
 * Prepare a new connection with necessary custom header fields.
 * @param request The request object.//from w  w  w. j av  a  2  s  .  c om
 *
 * @return A new url connection.
 * @throws IOException if an error occurs while opening the connection.
 */
public HttpURLConnection initConnection(Request request) throws IOException {
    // Generate signature using pre-shared key.
    RequestSigning.constructSignatureForRequestParameters(request.getParams(), request.getSecretKey());

    // Construct connection with necessary custom headers.
    URL url = constructUrlGetConnection(request.getParams(), request.getMethod(), request.getUrl());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setReadTimeout(Defaults.CONNECTION_READ_TIMEOUT);
    connection.setConnectTimeout(Defaults.CONNECTION_TIMEOUT);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.addRequestProperty(HTTP.CONTENT_ENCODING, Config.PARAMS_ENCODING);
    connection.addRequestProperty(BaseService.OS_FAMILY, Config.OS_ANDROID);
    connection.addRequestProperty(BaseService.OS_REVISION, DeviceProperties.getApiLevel());
    connection.addRequestProperty(BaseService.SDK_REVISION, Config.SDK_REVISION_CODE);

    return connection;
}

From source file:jp.go.nict.langrid.commons.protobufrpc.URLRpcChannel.java

public void call(BlockPE<OutputStream, IOException> sender, BlockPE<InputStream, IOException> successReceiver,
        BlockPPE<InputStream, IOException, IOException> failReceiver) {
    HttpURLConnection c = null;
    try {//from  w  ww  . j av a 2 s .  c  om
        c = (HttpURLConnection) url.openConnection();
        c.setDoOutput(true);
        for (Map.Entry<String, String> entry : requestProperties.entrySet()) {
            c.addRequestProperty(entry.getKey(), entry.getValue());
        }
        if (!requestProperties.containsKey(LangridConstants.HTTPHEADER_PROTOCOL)) {
            c.addRequestProperty(LangridConstants.HTTPHEADER_PROTOCOL, Protocols.PROTOBUF_RPC);
        }
        if (System.getProperty("http.proxyHost") != null) {
            String proxyAuthUser = System.getProperty("http.proxyUser");
            if (proxyAuthUser != null) {
                String proxyAuthPass = System.getProperty("http.proxyPassword");
                String header = proxyAuthUser + ":" + ((proxyAuthPass != null) ? proxyAuthPass : "");
                c.setRequestProperty("Proxy-Authorization",
                        "Basic " + new String(Base64.encodeBase64(header.getBytes())));
            }
        }
        if (authUserName != null && authUserName.length() > 0) {
            String header = authUserName + ":" + ((authPassword != null) ? authPassword : "");
            c.setRequestProperty("Authorization",
                    "Basic " + new String(Base64.encodeBase64(header.getBytes())));
        }
        OutputStream os = c.getOutputStream();
        try {
            sender.execute(os);
        } finally {
            os.close();
        }
        for (Map.Entry<String, List<String>> entry : c.getHeaderFields().entrySet()) {
            responseProperties.put(entry.getKey(),
                    StringUtil.join(entry.getValue().toArray(ArrayUtil.emptyStrings()), ", "));
        }
        InputStream is = c.getInputStream();
        try {
            successReceiver.execute(is);
        } finally {
            is.close();
        }
    } catch (IOException e) {
        InputStream es = null;
        if (c != null) {
            es = c.getErrorStream();
        }
        try {
            failReceiver.execute(es, e);
        } catch (IOException ee) {
        } finally {
            if (es != null) {
                try {
                    es.close();
                } catch (IOException ee) {
                }
            }
        }

    }
}