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.psbk.modulperwalian.Controller.DosenController.java

public List<Mahasiswa> getListMahasiswa() throws Exception {
    mhsList = 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;//w  w w.  j  a  v  a 2 s.  c om
    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");
        Mahasiswa s = new Mahasiswa();
        s.setNrp(result.getString("nrp"));
        s.setNama(result.getString("nama"));
        mhsList.add(s);
    }

    return mhsList;
}

From source file:com.psbk.modulperwalian.Controller.DosenController.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;/*from  w w  w  .  ja  v  a2  s  . co 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.matches("Tunda")) {
            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.psbk.modulperwalian.Controller.DosenController.java

public List<Perwalian> getDetailKrs() throws Exception {
    waliList = new ArrayList<>();
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
    String nrp = request.getParameter("nrp");
    String url = "mahasiswa/detailKontrakMk/01";
    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;//  w ww .  j a  v a2s .  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");
        Perwalian p = new Perwalian();
        p.getMhs().setNama(result.getString("nama"));
        p.getMhs().setNrp(result.getString("nrp"));
        p.getMk().setKode(result.getString("kode_mk"));

        waliList.add(p);

    }
    return waliList;
}

From source file:org.bsc.confluence.xmlrpc.XMLRPCApp.java

/**
 * //from   w  w  w .ja va  2  s. c om
 * @throws Exception 
 */
protected void usingHttp() throws Exception {

    ConfluenceProxy proxyInfo = null;

    final ConfluenceService.Credentials credentials = new ConfluenceService.Credentials(username /*args[1]*/,
            password/*args[2]*/);

    final SSLCertificateInfo sslInfo = new SSLCertificateInfo();

    final XMLRPCConfluenceServiceImpl confluence = XMLRPCConfluenceServiceImpl.createInstanceDetectingVersion(
            ConfluenceService.Protocol.XMLRPC.addTo(url), //args[0],
            credentials, proxyInfo, sslInfo);

    confluence.getPage("CIRC", "Best Movies").thenAccept(p -> {

        Model.Page page = p.orElseThrow(() -> new RuntimeException("page not found!"));

        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);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);
        }

    });

}

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

public List<Perwalian> getMhsHasPerwalian() 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;/*  w  ww  .j  ava  2  s. c  om*/
    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("terima")) {
            Perwalian p = new Perwalian();
            p.getMhs().setNama(result.getString("nama"));
            p.getMhs().setNrp(result.getString("nrp"));
            waliList.add(p);
        }

    }

    if (waliList.isEmpty()) {
        System.out.println("Kosong");
    }

    return waliList;
}

From source file:test.ShopThreadSrc.java

private HttpURLConnection getHttpPostConn(String url) throws Exception {
    URL obj = new URL(url);
    HttpURLConnection conn;
    conn = (HttpURLConnection) obj.openConnection();
    conn.setRequestMethod("POST");
    if (null != this.cookies) {
        conn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies));
    }/*w  w  w. j  ava2  s  . c  o m*/
    conn.setRequestProperty("Host", "consignment.5173.com");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
    conn.setRequestProperty("Referer", url);
    conn.setRequestProperty("Connection", "keep-alive");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    return conn;
}

From source file:common.net.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();

    stethoManager = new StethoURLConnectionManager(url);

    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);
    requestDecompression(connection);

    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());

    stethoManager.postConnect();

    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:io.mindmaps.engine.loader.DistributedLoader.java

private String executePost(HttpURLConnection connection, String body) {

    try {/* ww  w.ja  v  a2s . c  o m*/
        // create post
        connection.setRequestMethod(REST.HttpConn.POST_METHOD);
        connection.addRequestProperty(REST.HttpConn.CONTENT_TYPE, REST.HttpConn.APPLICATION_POST_TYPE);

        // add body and execute
        connection.setRequestProperty(REST.HttpConn.CONTENT_LENGTH, Integer.toString(body.length()));
        connection.getOutputStream().write(body.getBytes(REST.HttpConn.UTF8));

        // get response
        return connection.getResponseMessage();
    } catch (HTTPException e) {
        LOG.error(ErrorMessage.ERROR_IN_DISTRIBUTED_TRANSACTION.getMessage(connection.getURL().toString(),
                e.getStatusCode(), getResponseMessage(connection), body));
    } catch (IOException e) {
        LOG.error(ErrorMessage.ERROR_COMMUNICATING_TO_HOST.getMessage(connection.getURL().toString()));
    }

    return null;
}

From source file:io.mindmaps.loader.DistributedLoader.java

private String executePost(HttpURLConnection connection, String body) {

    try {/*from   w ww.j a  va2 s . c o  m*/
        // create post
        connection.setRequestMethod(RESTUtil.HttpConn.POST_METHOD);
        connection.addRequestProperty(RESTUtil.HttpConn.CONTENT_TYPE, RESTUtil.HttpConn.APPLICATION_POST_TYPE);

        // add body and execute
        connection.setRequestProperty(RESTUtil.HttpConn.CONTENT_LENGTH, Integer.toString(body.length()));
        connection.getOutputStream().write(body.getBytes(RESTUtil.HttpConn.UTF8));

        // get response
        return connection.getResponseMessage();
    } catch (HTTPException e) {
        LOG.error(ErrorMessage.ERROR_IN_DISTRIBUTED_TRANSACTION.getMessage(connection.getURL().toString(),
                e.getStatusCode(), getResponseMessage(connection), body));
    } catch (IOException e) {
        LOG.error(ErrorMessage.ERROR_COMMUNICATING_TO_HOST.getMessage(connection.getURL().toString()));
    }

    return null;
}

From source file:com.gargoylesoftware.htmlunit.UrlFetchWebConnection.java

/**
 * {@inheritDoc}/*w w  w .  jav a2s  .c o  m*/
 */
@Override
public WebResponse getResponse(final WebRequest webRequest) throws IOException {
    final long startTime = System.currentTimeMillis();
    final URL url = webRequest.getUrl();
    if (LOG.isTraceEnabled()) {
        LOG.trace("about to fetch URL " + url);
    }

    // hack for JS, about, and data URLs.
    final WebResponse response = produceWebResponseForGAEProcolHack(url);
    if (response != null) {
        return response;
    }

    // this is a "normal" URL
    try {
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //            connection.setUseCaches(false);
        connection.setConnectTimeout(webClient_.getOptions().getTimeout());

        connection.addRequestProperty("User-Agent", webClient_.getBrowserVersion().getUserAgent());
        connection.setInstanceFollowRedirects(false);

        // copy the headers from WebRequestSettings
        for (final Entry<String, String> header : webRequest.getAdditionalHeaders().entrySet()) {
            connection.addRequestProperty(header.getKey(), header.getValue());
        }
        addCookies(connection);

        final HttpMethod httpMethod = webRequest.getHttpMethod();
        connection.setRequestMethod(httpMethod.name());
        if (HttpMethod.POST == httpMethod || HttpMethod.PUT == httpMethod || HttpMethod.PATCH == httpMethod) {
            connection.setDoOutput(true);
            final String charset = webRequest.getCharset();
            connection.addRequestProperty("Content-Type", FormEncodingType.URL_ENCODED.getName());

            try (final OutputStream outputStream = connection.getOutputStream()) {
                final List<NameValuePair> pairs = webRequest.getRequestParameters();
                final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs);
                final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset);
                outputStream.write(query.getBytes(charset));
                if (webRequest.getRequestBody() != null) {
                    IOUtils.write(webRequest.getRequestBody().getBytes(charset), outputStream);
                }
            }
        }

        final int responseCode = connection.getResponseCode();
        if (LOG.isTraceEnabled()) {
            LOG.trace("fetched URL " + url);
        }

        final List<NameValuePair> headers = new ArrayList<>();
        for (final Map.Entry<String, List<String>> headerEntry : connection.getHeaderFields().entrySet()) {
            final String headerKey = headerEntry.getKey();
            if (headerKey != null) { // map contains entry like (null: "HTTP/1.1 200 OK")
                final StringBuilder sb = new StringBuilder();
                for (final String headerValue : headerEntry.getValue()) {
                    if (sb.length() != 0) {
                        sb.append(", ");
                    }
                    sb.append(headerValue);
                }
                headers.add(new NameValuePair(headerKey, sb.toString()));
            }
        }

        final byte[] byteArray;
        try (final InputStream is = responseCode < 400 ? connection.getInputStream()
                : connection.getErrorStream()) {
            byteArray = IOUtils.toByteArray(is);
        }

        final long duration = System.currentTimeMillis() - startTime;
        final WebResponseData responseData = new WebResponseData(byteArray, responseCode,
                connection.getResponseMessage(), headers);
        saveCookies(url.getHost(), headers);
        return new WebResponse(responseData, webRequest, duration);
    } catch (final IOException e) {
        LOG.error("Exception while tyring to fetch " + url, e);
        throw new RuntimeException(e);
    }
}