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:org.apache.streams.moreover.MoreoverClient.java

private String getArticles2(URL url) throws IOException {
    HttpURLConnection cn = (HttpURLConnection) url.openConnection();
    cn.setRequestMethod("GET");
    cn.addRequestProperty("Content-Type", "text/xml;charset=UTF-8");
    cn.setDoInput(true);/* ww w.  ja v a2s. c om*/
    cn.setDoOutput(false);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(cn.getInputStream(), Charset.forName("UTF-8")));
    String line = null;
    StringBuilder builder = new StringBuilder();
    String result = new String("".getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"));
    while ((line = reader.readLine()) != null) {
        result += line;
    }
    pullTime = new Date().getTime();
    return result;
}

From source file:cn.bidaround.ytcore.util.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  ww.  ja v a 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");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:com.cloudbees.mtslaves.client.RemoteReference.java

protected HttpURLConnection open(String relUrl) throws IOException {
    URL u = getEntityUrl(relUrl);
    HttpURLConnection con = (HttpURLConnection) u.openConnection();
    con.addRequestProperty("Accept", "application/json");
    this.token.authorizeRequest(con);
    con.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MS);
    con.setReadTimeout(DEFAULT_READ_TIMEOUT_MS);

    return con;/*from  w w w .j a  v  a2 s.  c  o m*/
}

From source file:org.dcm4che3.tool.wadors.WadoRS.java

private static SimpleHTTPResponse sendRequest(final WadoRS main) throws IOException {
    URL newUrl = new URL(main.getUrl());

    LOG.info("WADO-RS URL: {}", newUrl);

    HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection();

    connection.setDoOutput(true);/*from w  w w .j a  v a2s .com*/

    connection.setDoInput(true);

    connection.setInstanceFollowRedirects(false);

    connection.setRequestMethod("GET");

    connection.setRequestProperty("charset", "utf-8");

    String[] acceptHeaders = compileAcceptHeader(main.acceptTypes);

    LOG.info("Accept-Headers: {}", Arrays.toString(acceptHeaders));

    for (String acceptStr : acceptHeaders)
        connection.addRequestProperty("Accept", acceptStr);

    if (main.getRequestTimeOut() != null) {
        connection.setConnectTimeout(Integer.valueOf(main.getRequestTimeOut()));
        connection.setReadTimeout(Integer.valueOf(main.getRequestTimeOut()));
    }

    connection.setUseCaches(false);

    int responseCode = connection.getResponseCode();
    String responseMessage = connection.getResponseMessage();

    boolean isErrorCase = responseCode >= HttpURLConnection.HTTP_BAD_REQUEST;
    if (!isErrorCase) {

        InputStream in = null;
        if (connection.getHeaderField("content-type").contains("application/json")
                || connection.getHeaderField("content-type").contains("application/zip")) {
            String headerPath;
            in = connection.getInputStream();
            if (main.dumpHeader)
                headerPath = writeHeader(connection.getHeaderFields(),
                        new File(main.outDir, "out.json" + "-head"));
            else {
                headerPath = connection.getHeaderField("content-location");
            }
            File f = new File(main.outDir,
                    connection.getHeaderField("content-type").contains("application/json") ? "out.json"
                            : "out.zip");
            Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
            main.retrievedInstances.put(headerPath, f.toPath().toAbsolutePath());
        } else {
            if (main.dumpHeader)
                dumpHeader(main, connection.getHeaderFields());
            in = connection.getInputStream();
            try {
                File spool = new File(main.outDir, "Spool");
                Files.copy(in, spool.toPath(), StandardCopyOption.REPLACE_EXISTING);
                String boundary;
                BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(spool)));
                boundary = (rdr.readLine());
                boundary = boundary.substring(2, boundary.length());
                rdr.close();
                FileInputStream fin = new FileInputStream(spool);
                new MultipartParser(boundary).parse(fin, new MultipartParser.Handler() {

                    @Override
                    public void bodyPart(int partNumber, MultipartInputStream partIn) throws IOException {

                        Map<String, List<String>> headerParams = partIn.readHeaderParams();
                        String mediaType;
                        String contentType = headerParams.get("content-type").get(0);

                        if (contentType.contains("transfer-syntax"))
                            mediaType = contentType.split(";")[0];
                        else
                            mediaType = contentType;

                        // choose writer
                        if (main.isMetadata) {
                            main.writerType = ResponseWriter.XML;

                        } else {
                            if (mediaType.equalsIgnoreCase("application/dicom")) {
                                main.writerType = ResponseWriter.DICOM;
                            } else if (isBulkMediaType(mediaType)) {
                                main.writerType = ResponseWriter.BULK;
                            } else {
                                throw new IllegalArgumentException("Unknown media type "
                                        + "returned by server, media type = " + mediaType);
                            }

                        }
                        try {
                            main.writerType.readBody(main, partIn, headerParams);
                        } catch (Exception e) {
                            System.out.println("Error parsing media type to determine extension" + e);
                        }
                    }

                    private boolean isBulkMediaType(String mediaType) {
                        if (mediaType.contains("octet-stream"))
                            return true;
                        for (Field field : MediaTypes.class.getFields()) {
                            try {
                                if (field.getType().equals(String.class)) {
                                    String tmp = (String) field.get(field);
                                    if (tmp.equalsIgnoreCase(mediaType))
                                        return true;
                                }
                            } catch (Exception e) {
                                System.out.println("Error deciding media type " + e);
                            }
                        }

                        return false;
                    }
                });
                fin.close();
                spool.delete();
            } catch (Exception e) {
                System.out.println("Error parsing Server response - " + e);
            }
        }

    } else {
        LOG.error("Server returned {} - {}", responseCode, responseMessage);
    }

    connection.disconnect();

    main.response = new WadoRSResponse(responseCode, responseMessage, main.retrievedInstances);
    return new SimpleHTTPResponse(responseCode, responseMessage);

}

From source file:org.apache.streams.data.moreover.MoreoverClient.java

private String getArticles(URL url) throws IOException {
    HttpURLConnection cn = (HttpURLConnection) url.openConnection();
    cn.setRequestMethod("GET");
    cn.addRequestProperty("Content-Type", "text/xml;charset=UTF-8");
    cn.setDoInput(true);/*from   w w  w  .j a v  a  2  s .c  o  m*/
    cn.setDoOutput(false);
    StringWriter writer = new StringWriter();
    IOUtils.copy(new InputStreamReader(cn.getInputStream(), Charset.forName("UTF-8")), writer);
    writer.flush();
    pullTime = new Date().getTime();

    // added after seeing java.net.SocketException: Too many open files
    cn.disconnect();

    return writer.toString();
}

From source file:com.selene.volley.stack.HurlStack.java

@SuppressWarnings("deprecation")
private 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);/* w ww .  j a v a2  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");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:org.apache.streams.data.moreover.MoreoverClient.java

private String getArticles2(URL url) throws IOException {
    HttpURLConnection cn = (HttpURLConnection) url.openConnection();
    cn.setRequestMethod("GET");
    cn.addRequestProperty("Content-Type", "text/xml;charset=UTF-8");
    cn.setDoInput(true);/*  w  w w.j ava 2  s .  c om*/
    cn.setDoOutput(false);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(cn.getInputStream(), Charset.forName("UTF-8")));
    String line = null;
    StringBuilder builder = new StringBuilder();
    String s = "";
    String result = new String(s.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"));
    while ((line = reader.readLine()) != null) {
        result += line;
    }
    pullTime = new Date().getTime();
    return result;
}

From source file:com.psbk.modulperwalian.Controller.DosenMain.java

public List<Perwalian> getMhsNotPerwalian() throws Exception {
    waliList = new ArrayList<>();
    String url = "dosen/getMhsWali/dos01";
    obj = new URL(BASE_URL + url);
    HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
    connection.setRequestMethod("GET");
    connection.addRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4=");
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;/*  ww  w.j  a  v a  2 s.  c  o  m*/
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }

    in.close();
    JSONObject result;
    JSONObject jsonObject = new JSONObject(response.toString());
    JSONArray jsonArray = (JSONArray) jsonObject.get("result");

    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject objek = (JSONObject) jsonArray.get(i);
        result = (JSONObject) objek.get("map");
        String status = result.getString("status");
        if (status.equals("belum")) {
            Perwalian p = new Perwalian();
            p.getMhs().setNama(result.getString("nama"));
            p.getMhs().setNrp(result.getString("nrp"));
            waliList.add(p);
        }

    }

    return waliList;
}

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

@SuppressWarnings("deprecation")
/* package */static void setConnectionParametersForRequest(final HttpURLConnection connection,
        final 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.
        final 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());
            final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);/*from   w  ww. j a  v a  2  s. co 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:
        addBodyIfExists(connection, request);
        connection.setRequestMethod("PATCH");
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:com.yaozu.object.volley.toolbox.HurlStack.java

@SuppressWarnings("deprecation")
/* package */static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Request.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);/*  w  w  w.  j  av  a2 s  .  com*/
            out.close();
        }
        break;
    case Request.Method.GET:
        // Not necessary to set the request method because connection
        // defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Request.Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Request.Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Request.Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Request.Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Request.Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Request.Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Request.Method.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}