Example usage for java.net HttpURLConnection getRequestProperties

List of usage examples for java.net HttpURLConnection getRequestProperties

Introduction

In this page you can find the example usage for java.net HttpURLConnection getRequestProperties.

Prototype

public Map<String, List<String>> getRequestProperties() 

Source Link

Document

Returns an unmodifiable Map of general request properties for this connection.

Usage

From source file:com.snaplogic.snaps.lunex.RequestProcessor.java

public String execute(RequestBuilder rBuilder) throws MalformedURLException, IOException {
    try {/*from   w w w  .  j a  va2  s  .  co m*/
        URL api_url = new URL(rBuilder.getURL());
        HttpURLConnection httpUrlConnection = (HttpURLConnection) api_url.openConnection();
        httpUrlConnection.setRequestMethod(rBuilder.getMethod().toString());
        httpUrlConnection.setDoInput(true);
        httpUrlConnection.setDoOutput(true);
        if (rBuilder.getSnapType() != LunexSnaps.Read) {
            rBuilder.getHeaders().add(Pair.of(CONTENT_LENGTH, rBuilder.getRequestBodyLenght()));
        }
        for (Pair<String, String> header : rBuilder.getHeaders()) {
            if (!StringUtils.isEmpty(header.getKey()) && !StringUtils.isEmpty(header.getValue())) {
                httpUrlConnection.setRequestProperty(header.getKey(), header.getValue());
            }
        }
        log.debug(String.format(LUNEX_HTTP_INFO, rBuilder.getSnapType(), rBuilder.getURL(),
                httpUrlConnection.getRequestProperties().toString()));
        if (rBuilder.getSnapType() != LunexSnaps.Read) {
            String paramsJson = null;
            if (!StringUtils.isEmpty(paramsJson = rBuilder.getRequestBody())) {
                DataOutputStream cgiInput = new DataOutputStream(httpUrlConnection.getOutputStream());
                log.debug(String.format(LUNEX_HTTP_REQ_INFO, paramsJson));
                cgiInput.writeBytes(paramsJson);
                cgiInput.flush();
                IOUtils.closeQuietly(cgiInput);
            }
        }

        List<String> input = null;
        StringBuilder response = new StringBuilder();
        try (InputStream iStream = httpUrlConnection.getInputStream()) {
            input = IOUtils.readLines(iStream);
        } catch (IOException ioe) {
            log.warn(String.format(INPUT_STREAM_ERROR, ioe.getMessage()));
            try (InputStream eStream = httpUrlConnection.getErrorStream()) {
                if (eStream != null) {
                    input = IOUtils.readLines(eStream);
                } else {
                    response.append(String.format(INPUT_STREAM_ERROR, ioe.getMessage()));
                }
            } catch (IOException ioe1) {
                log.warn(String.format(INPUT_STREAM_ERROR, ioe1.getMessage()));
            }
        }
        statusCode = httpUrlConnection.getResponseCode();
        log.debug(String.format(HTTP_STATUS, statusCode));
        if (input != null && !input.isEmpty()) {
            for (String line : input) {
                response.append(line);
            }
        }
        return formatResponse(response, rBuilder);
    } catch (MalformedURLException me) {
        log.error(me.getMessage(), me);
        throw me;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        throw ioe;
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        throw ex;
    }
}

From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java

protected String request(HttpMethod httpMethod, URL url, int timeout, IResource resource)
        throws SocketTimeoutException, HttpClientException {
    HttpURLConnection connection = null;
    try {//from www . jav  a2 s  . c  o  m
        connection = createConnection(url, userAgent, acceptedVersion, acceptedMediaType,
                sslAuthorizationCallback, timeout);
        if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT) {
            setContentTypeHeader(acceptedVersion, acceptedMediaType, connection);
        }
        // PATCH not yet supported by JVM
        setRequestMethod(httpMethod, connection);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Request Properties: %s", connection.getRequestProperties()));
            LOGGER.debug(String.format("Request Method: %s", connection.getRequestMethod()));
        }
        if (resource != null) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(resource.toJson(false));
            connection.setDoOutput(true);
            PrintWriter writer = new PrintWriter(connection.getOutputStream());
            writer.write(resource.toString());
            writer.flush();
        }
        return IOUtils.toString(connection.getInputStream(), "UTF-8");
    } catch (SocketTimeoutException e) {
        throw e;
    } catch (IOException e) {
        throw createException(e, connection);
    } finally {
        disconnect(connection);
    }
}

From source file:test.ShopThreadSrc.java

private HttpURLConnection getHttpGetConn(String url) throws Exception {
    HttpURLConnection conn;
    // Acts like a browser
    URL obj = new URL(url);
    conn = (HttpURLConnection) obj.openConnection();
    if (null != this.cookies) {
        conn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies));
    }//from www  .  j a  v a 2  s  . c om
    conn.setRequestMethod("GET");
    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("Connection", "keep-alive");
    conn.setRequestProperty("Host", "consignment.5173.com");
    conn.setRequestProperty("Referer", url);
    System.out.println(conn.getRequestProperties());
    return conn;
}

From source file:com.dao.ShopThread.java

private String getPayKey(HttpURLConnection conn, String type) throws Exception {
    LogUtil.debugPrintf("");
    String keyurl = conn.getURL().toString();
    String postParams = getKeyDynamicParams(keyurl, type);
    HttpURLConnection loginConn = getHttpPostConn(keyurl);
    loginConn.setRequestProperty("Accept-Encoding", "deflate");// ??
    loginConn.setRequestProperty("Referer", keyurl);
    loginConn.setRequestProperty("Host", "danbao.5173.com");
    loginConn.setRequestProperty("Pragma", "no-cache");
    loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
    LogUtil.debugPrintf("?keyHEADER===" + loginConn.getRequestProperties());
    LogUtil.debugPrintf("?keypostParams===" + postParams);
    DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream());
    wr.writeBytes(postParams);/*from   w  ww .  j a  va  2  s.  com*/
    wr.flush();
    wr.close();
    BufferedReader in = new BufferedReader(new InputStreamReader(loginConn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer(2000);
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    String payurl = response.toString();
    LogUtil.debugPrintf("keyHtml:" + payurl);
    payurl = payurl.substring(payurl.indexOf("action") + "action".length(), payurl.indexOf("></form>"));
    payurl = payurl.substring(payurl.indexOf("\"") + 1, payurl.lastIndexOf("\""));
    Map<String, List<String>> header = loginConn.getHeaderFields();
    LogUtil.debugPrintf("?key?HEADER===" + header);
    List<String> cookie = header.get("Set-Cookie");
    if (cookie == null || cookie.size() == 0) {
        LogUtil.debugPrintf("?keycookie----------->");
    } else {
        LogUtil.debugPrintf("?keycookie----------->");
        LogUtil.debugPrintf("cookie====" + cookie);
        setCookies(cookie);
    }
    LogUtil.debugPrintf("?key?----------->");
    return payurl;
}

From source file:com.cloudant.http.internal.interceptors.CookieInterceptor.java

@Override
public HttpConnectionInterceptorContext interceptRequest(HttpConnectionInterceptorContext context) {

    HttpURLConnection connection = context.connection.getConnection();

    // First time we will have no cookies
    if (cookieManager.getCookieStore().getCookies().isEmpty() && shouldAttemptCookieRequest.get()) {
        if (!requestCookie(context)) {
            // Requesting a cookie failed, set a flag if we failed so we won't try again
            shouldAttemptCookieRequest.set(false);
        }//from   w ww  .  j ava  2  s . c  o m
    }

    if (shouldAttemptCookieRequest.get()) {

        // Debug logging
        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("Attempt to add cookie to request.");
            logger.finest("Cookies are stored for URIs: " + cookieManager.getCookieStore().getURIs());
        }

        // Apply any saved cookies to the request
        try {
            Map<String, List<String>> requestCookieHeaders = cookieManager.get(connection.getURL().toURI(),
                    connection.getRequestProperties());
            for (Map.Entry<String, List<String>> requestCookieHeader : requestCookieHeaders.entrySet()) {
                List<String> cookies = requestCookieHeader.getValue();
                if (cookies != null && !cookies.isEmpty()) {
                    connection.setRequestProperty(requestCookieHeader.getKey(),
                            listToSemicolonSeparatedString(cookies));
                } else {
                    logger.finest("No cookie values to set.");
                }
            }
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Failed to read request properties", e);
        } catch (URISyntaxException e) {
            logger.log(Level.SEVERE, "Failed to convert request URL to URI for cookie " + "retrieval.");
        }
    }
    return context;
}

From source file:easyshop.downloadhelper.HttpPageGetter.java

public HttpPage getDHttpPage(PageRef url, String charSet) {
    count++;//from  w  ww.j  av a  2 s .c om
    log.debug("getURL(" + count + ")");

    if (url.getUrlStr() == null) {
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new OriHttpPage(-1, null, null, null, conRes, null);
    }
    URL requestedURL = null;
    try {
        requestedURL = new URL(url.getUrlStr());
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        log.error("wrong urlstr" + url.getUrlStr());
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new OriHttpPage(-1, null, null, null, conRes, null);
    }
    ;
    //        System.out.println(""+requestedURL.toExternalForm());
    URL referer = null;
    try {
        log.debug("Creating HTTP connection to " + requestedURL);
        HttpURLConnection conn = (HttpURLConnection) requestedURL.openConnection();
        if (referer != null) {
            log.debug("Setting Referer header to " + referer);
            conn.setRequestProperty("Referer", referer.toExternalForm());
        }

        if (userAgent != null) {
            log.debug("Setting User-Agent to " + userAgent);
            conn.setRequestProperty("User-Agent", userAgent);
        }

        //            DateFormat dateFormat=DateFormat.getDateInstance();
        //            conn.setRequestProperty("If-Modlfied-Since",dateFormat.parse("2005-08-15 20:18:30").toGMTString());
        conn.setUseCaches(false);

        //            conn.setRequestProperty("connection","keep-alive");
        for (Iterator it = conn.getRequestProperties().keySet().iterator(); it.hasNext();) {
            String key = (String) it.next();
            if (key == null) {
                break;
            }
            String value = conn.getHeaderField(key);
            //                System.out.println("Request header " + key + ": " + value);
        }
        log.debug("Opening URL");
        long startTime = System.currentTimeMillis();
        conn.connect();

        String resp = conn.getResponseMessage();
        log.debug("Remote server response: " + resp);

        int code = conn.getResponseCode();

        if (code != 200) {
            log.error("Could not get connection for code=" + code);
            System.err.println("Could not get connection for code=" + code);
            ConnResponse conRes = new ConnResponse(null, null, 0, 0, code);
            return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
        }

        //            if (conn.getContentLength()<=0||conn.getContentLength()>10000000){
        //               log.error("Content length==0");
        //               System.err.println("Content length==0");
        //               ConnResponse conRes=new ConnResponse(null,null,null,0,0,-100);
        //               return new URLObject(-1,requestedURL, null,null,conRes);
        //            }

        String respStr = conn.getHeaderField(0);
        long serverDate = conn.getDate();
        //            log.info("Server response: " + respStr);

        for (int i = 1; i < conn.getHeaderFields().size(); i++) {
            String key = conn.getHeaderFieldKey(i);
            if (key == null) {
                break;
            }
            String value = conn.getHeaderField(key);
            //                System.out.println("Received header " + key + ": " + value);
            //               log.debug("Received header " + key + ": " + value);
        }

        //            log.debug("Getting buffered input stream from remote connection");
        log.debug("start download(" + count + ")");
        BufferedInputStream remoteBIS = new BufferedInputStream(conn.getInputStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream(10240);
        byte[] buf = new byte[1024];
        int bytesRead = 0;
        while (bytesRead >= 0) {
            baos.write(buf, 0, bytesRead);
            bytesRead = remoteBIS.read(buf);
        }
        //            baos.write(remoteBIS.read(new byte[conn.getContentLength()]));
        //            remoteBIS.close();
        byte[] content = baos.toByteArray();
        long timeTaken = System.currentTimeMillis() - startTime;
        if (timeTaken < 100)
            timeTaken = 500;

        int bytesPerSec = (int) ((double) content.length / ((double) timeTaken / 1000.0));
        //            log.info("Downloaded " + content.length + " bytes, " + bytesPerSec + " bytes/sec");
        if (content.length < conn.getContentLength()) {
            log.warn("Didn't download full content for URL: " + url);
            //                failureCount++;
            ConnResponse conRes = new ConnResponse(conn.getContentType(), null, content.length, serverDate,
                    code);
            return new HttpPage(requestedURL.toExternalForm(), null, conRes, conn.getContentType());
        }

        log.debug("download(" + count + ")");

        ConnResponse conRes = new ConnResponse(conn.getContentType(), null, conn.getContentLength(), serverDate,
                code);
        String c = charSet;
        if (c == null)
            c = conRes.getCharSet();
        HttpPage obj = new HttpPage(requestedURL.toExternalForm(), content, conRes, c);
        return obj;
    } catch (IOException ioe) {
        log.warn("Caught IO Exception: " + ioe.getMessage(), ioe);
        failureCount++;
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
    } catch (Exception e) {
        log.warn("Caught Exception: " + e.getMessage(), e);
        failureCount++;
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
    }
}

From source file:org.opentestsystem.shared.test.interactioncontext.FastInteractionContext.java

public FastInteractionResponse buildResponse(String method, URL url, Map<String, List<String>> headers,
        Reader body, long timeout) throws IOException {

    URI uri = null;/*from  w  ww  .java 2s. c om*/
    try {
        uri = url.toURI();
    } catch (URISyntaxException e) {
        synchronized (this) {
            getActiveTimingRecord().fail(String.format("Invalid URL: %s", url.toString()), e);
        }
    }

    int iTimeout = (int) Math.min(Integer.MAX_VALUE, timeout);

    FastInteractionResponse response = null;
    HttpURLConnection connection = null;

    // This value is only used if an error causes things to fail before the connection is created.
    long t_start = System.currentTimeMillis();
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(iTimeout);
        connection.setReadTimeout(iTimeout);

        // Expect to send ouptut if a body has been supplied
        connection.setDoOutput(body != null);

        // Set headers (except cookies)
        if (headers != null) {
            for (Entry<String, List<String>> header_i : headers.entrySet()) {
                connection.setRequestProperty(header_i.getKey(), StringUtils.join(header_i.getValue(), ','));
            }
        } else {
            headers = new HashMap<String, List<String>>();
        }

        // Set cookies
        for (Entry<String, List<String>> header_i : _cookies.get(uri, headers).entrySet()) {
            for (String cookie_j : header_i.getValue()) {
                connection.addRequestProperty(header_i.getKey(), cookie_j);
            }
        }

        // Log the request, if desired
        if (_logger.isDebugEnabled()) {
            StringBuilder msg = new StringBuilder("Posted HTTP request:\r\n\r\n");
            msg.append(method).append("\r\n");
            msg.append(uri.toString()).append("\r\n");
            for (Entry<String, List<String>> header_i : connection.getRequestProperties().entrySet()) {
                for (String value_j : header_i.getValue())
                    msg.append(header_i.getKey()).append(": ").append(value_j).append("\r\n");
            }
            msg.append("\r\n");

            if (body != null) {
                String bodyString = IOUtils.toString(body);
                IOUtils.closeQuietly(body);
                body = new StringReader(bodyString);
                msg.append(bodyString);
            }

            _logger.debug(msg.toString());
        }

        // Start timing
        // We update here because we don't really want to count time spent above.
        t_start = System.currentTimeMillis();

        // Send the request
        connection.connect();

        // Send the body
        if (body != null) {
            try (OutputStream os = connection.getOutputStream();) {
                IOUtils.copy(body, os, "UTF-8");
            } finally {
                IOUtils.closeQuietly(body);
            }
        }

        // Record the cookies
        // SB-547 workaround: multiple set-cookie headers are sent for the same
        // cookie. Process the last.
        Map<String, String> cookieMap = new HashMap<>();
        for (Entry<String, List<String>> header_i : connection.getHeaderFields().entrySet()) {
            if (StringUtils.equals(header_i.getKey(), "Set-Cookie")) {
                for (String value_j : header_i.getValue()) {
                    for (String value_k : StringUtils.split(value_j, ',')) {
                        String[] cookieParts = StringUtils.split(value_k, "=", 2);
                        if (cookieParts.length > 0) {
                            String oldValue = cookieMap.get(cookieParts[0]);
                            if (oldValue == null || oldValue.length() < value_k.length()) {
                                cookieMap.put(cookieParts[0], value_k);
                            }
                        }
                    }
                }
            }
        }
        List<String> cookieValues = new ArrayList<>(cookieMap.values());
        Map<String, List<String>> cookieHeaders = new HashMap<>();
        cookieHeaders.put("Set-Cookie", cookieValues);
        _cookies.put(uri, cookieHeaders);

        // Retrieve the response
        InputStream is = connection.getInputStream();
        response = new FastInteractionResponse(this, is, connection, timeout, t_start + timeout);
        IOUtils.closeQuietly(is);
        connection.disconnect();

        // Stop timing
        long t_end = System.currentTimeMillis();
        synchronized (this) {
            InteractionTimingRecord timingRecord = getActiveTimingRecord();
            if (timingRecord != null) {
                timingRecord.accumulate("REMOTE_TIME", t_end - t_start);
                timingRecord.accumulate("N_REQ", 1);
            }
        }

        // Log the response, if desired
        if (_logger.isDebugEnabled()) {
            StringBuilder msg = new StringBuilder("Response from HTTP request:\r\n\r\n");
            msg.append(uri.toString()).append("\r\n\r\n");
            for (Entry<String, List<String>> header_i : connection.getHeaderFields().entrySet()) {
                for (String value_j : header_i.getValue()) {
                    msg.append(header_i.getKey()).append(": ").append(value_j).append("\r\n");
                }
            }
            msg.append("\r\n");
            String bodyString = response.getResponseBodyAsString();
            if (bodyString != null) {
                if (bodyString.length() <= 1024) {
                    msg.append(bodyString);
                } else {
                    msg.append(String.format("Body length %d. Showing first 1024 characters\r\n\r\n",
                            bodyString.length()));
                    msg.append(bodyString.subSequence(0, 1024));
                }
            }
            _logger.debug(msg.toString());
        }

        return response;
    } catch (IOException e) {
        synchronized (this) {
            failActiveInteraction(String.format("IO Error trying to fill request to %s", url.toString()), e);
            InputStream es = null;
            es = connection.getErrorStream();
            response = new FastInteractionResponse(this, es, connection, timeout, t_start + timeout);
            IOUtils.closeQuietly(es);
        }
    }
    return response;
}

From source file:org.jboss.tools.ws.ui.utils.JAXRSTester.java

/**
 * Call a JAX-RS service/*from   w w  w . ja va 2 s. co m*/
 * @param address
 * @param parameters
 * @param headers
 * @param methodType
 * @param requestBody
 * @param proxy
 * @param port
 * @throws Exception
 */
public void doTest(String address, Map<String, String> parameters, Map<String, String> headers,
        String methodType, String requestBody, String proxy, int port, String uid, String pwd)
        throws Exception {

    // handle the proxy
    Proxy proxyObject = null;
    if (proxy != null && proxy.length() > 0 && port > 0) {
        InetSocketAddress proxyAddress = new InetSocketAddress(proxy, port);
        proxyObject = new Proxy(Proxy.Type.HTTP, proxyAddress);
    }

    // clear the returned results
    resultBody = EMPTY_STRING;

    // get the parms string
    String query = buildWebQuery(parameters);

    // Clear the address of any leading/trailing spaces
    address = address.trim();

    // build the complete URL
    URL url = null;
    if (query != null && query.trim().length() > 0) {
        // add the ? if there are parameters
        if (!address.endsWith("?") && !address.contains("?")) {//$NON-NLS-1$ //$NON-NLS-2$

            // if we're a "GET" - add the ? by default
            if (methodType.equalsIgnoreCase("GET")) { //$NON-NLS-1$
                address = address + "?"; //$NON-NLS-1$

                // if we're a PUT or POST, check if we have parms
                // and add the ? if we do
            } else if (methodType.equalsIgnoreCase("POST")//$NON-NLS-1$ 
                    || methodType.equalsIgnoreCase("PUT") //$NON-NLS-1$
                    || methodType.equalsIgnoreCase("DELETE")) { //$NON-NLS-1$
                if (query.trim().length() > 0) {
                    address = address + "?"; //$NON-NLS-1$
                }
            }
        } else if (address.contains("?")) { //$NON-NLS-1$
            address = address + "&"; //$NON-NLS-1$
        }
        // add parms to the url if we have some
        url = new URL(address + query);
    } else {
        url = new URL(address);
    }

    // make connection
    HttpURLConnection httpurlc = null;
    if (proxyObject == null) {
        httpurlc = (HttpURLConnection) url.openConnection();
    } else {
        // if have proxy, pass it along
        httpurlc = (HttpURLConnection) url.openConnection(proxyObject);
    }

    // since we are expecting output back, set to true
    httpurlc.setDoOutput(true);

    // not sure what this does - may be used for authentication?
    httpurlc.setAllowUserInteraction(false);

    // set whether this is a GET or POST
    httpurlc.setRequestMethod(methodType);

    // if we have headers to add
    if (headers != null && !headers.isEmpty()) {
        Iterator<?> iter = headers.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<?, ?> entry = (Entry<?, ?>) iter.next();
            if (entry.getKey() != null && entry.getKey() instanceof String)
                httpurlc.addRequestProperty((String) entry.getKey(), (String) entry.getValue());
        }
    }

    // if we have basic authentication to add, add it!
    if (uid != null && pwd != null) {
        String authStr = uid + ':' + pwd;
        byte[] authEncByte = Base64.encodeBase64(authStr.getBytes());
        String authStringEnc = new String(authEncByte);
        httpurlc.addRequestProperty("Authorization", "Basic " + authStringEnc); //$NON-NLS-1$//$NON-NLS-2$
    }

    requestHeaders = httpurlc.getRequestProperties();

    // Check if task has been interrupted
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    // CONNECT!
    httpurlc.connect();

    // Check if task has been interrupted
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    // If we are doing a POST and we have some request body to pass along, do it
    if (requestBody != null && (methodType.equalsIgnoreCase("POST") //$NON-NLS-1$
            || methodType.equalsIgnoreCase("PUT"))) { //$NON-NLS-1$
        requestBody = WSTestUtils.stripNLsFromXML(requestBody);
        OutputStreamWriter out = new OutputStreamWriter(httpurlc.getOutputStream());
        String stripped = stripCRLF(requestBody);
        out.write(stripped);
        out.close();
    }

    // Check if task has been interrupted
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    // if we have headers to pass to user, copy them
    if (httpurlc.getHeaderFields() != null) {
        resultHeaders = httpurlc.getHeaderFields();
    }

    // retrieve result and put string results into the response
    InputStream is = null;
    try {
        is = httpurlc.getInputStream();
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));//$NON-NLS-1$
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");//$NON-NLS-1$
        }
        br.close();
        resultBody = sb.toString();
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    } catch (IOException ie) {
        try {
            is = httpurlc.getErrorStream();

            // is possible that we're getting nothing back in the error stream
            if (is != null) {
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));//$NON-NLS-1$
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    sb.append("\n");//$NON-NLS-1$
                }
                br.close();
                resultBody = sb.toString();
            }
        } catch (IOException ie2) {
            resultBody = ie2.getLocalizedMessage();
        }
    }

    // as a last resort, if we still have nothing to report,
    // show an error message to the user
    if (resultBody == null || resultBody.trim().isEmpty()) {
        resultBody = JBossWSUIMessages.JAXRSRSTestView_Message_Unsuccessful_Test;
    }

    // disconnect explicitly (may not be necessary)
    httpurlc.disconnect();
}

From source file:com.sandklef.coachapp.http.HttpAccess.java

public void uploadTrainingPhaseVideo(String clubUri, String videoUuid, String fileName)
        throws HttpAccessException, IOException {

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String pathToOurFile = fileName;
    String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.PATH_SEPARATOR
            + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR
            + HttpSettings.UPLOAD_PATH;//  w  ww . j av a2 s .  com

    Log.d(LOG_TAG, "Upload server url: " + urlServer);
    Log.d(LOG_TAG, "Upload file:       " + fileName);

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;

    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    Log.d(LOG_TAG, "connection: " + connection + "  uploading data to video: " + videoUuid);

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestMethod(HttpSettings.HTTP_POST);

    //
    int timeout = LocalStorage.getInstance().getnetworkTimeout();
    Log.d(LOG_TAG, "timeout: " + timeout);
    connection.setConnectTimeout(timeout);
    connection.setReadTimeout(timeout);

    connection.setRequestProperty("X-Token", LocalStorage.getInstance().getLatestUserToken());
    connection.addRequestProperty("X-Instance", LocalStorage.getInstance().getCurrentClub());
    connection.setRequestProperty("Connection", "close");

    Log.d(LOG_TAG, " upload propoerties: " + connection.getRequestProperties());

    outputStream = new DataOutputStream(connection.getOutputStream());
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0) {
        Log.d(LOG_TAG, " writing data to stream  (" + bytesRead + " / " + bytesAvailable + ")");
        outputStream.write(buffer, 0, bufferSize);
        Log.d(LOG_TAG, " writing data to stream  -");
        bytesAvailable = fileInputStream.available();
        Log.d(LOG_TAG, " writing data to stream  -");
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
    outputStream.flush();
    outputStream.close();

    // Responses from the server (code and message)
    fileInputStream.close();

    int serverResponseCode = 0;

    long before = System.currentTimeMillis();
    try {
        Log.d(LOG_TAG, " ... writing done, getting response code");
        serverResponseCode = connection.getResponseCode();
        Log.d(LOG_TAG, " ... writing done, getting response message");
        String serverResponseMessage = connection.getResponseMessage();
        Log.d(LOG_TAG, "ServerCode:" + serverResponseCode);
        Log.d(LOG_TAG, "serverResponseMessage:" + serverResponseMessage);
    } catch (java.net.SocketTimeoutException e) {
        Log.d(LOG_TAG, " ... getting response code, got an exception, print stacktrace");
        e.printStackTrace();
        throw new HttpAccessException("Network timeout reached", e, HttpAccessException.NETWORK_SLOW);
    }
    long after = System.currentTimeMillis();
    long diff = after - before;
    Log.d(LOG_TAG, "diff: " + diff + "ms   " + diff / 1000 + "s");

    if (diff > LocalStorage.getInstance().getnetworkTimeout()) {
        throw new HttpAccessException("Network timeout reached", HttpAccessException.NETWORK_SLOW);
    }

    if (serverResponseCode >= 409) {
        throw new HttpAccessException("Failed uploading trainingphase video, access denied",
                HttpAccessException.CONFLICT_ERROR);
    }

    if (serverResponseCode < 500 && serverResponseCode >= 400) {
        throw new HttpAccessException("Failed uploading trainingphase video, access denied",
                HttpAccessException.ACCESS_ERROR);
    }

    try {
        Log.d(LOG_TAG, " ... disconnecting");
        connection.disconnect();
    } catch (Exception e) {
        Log.d(LOG_TAG, " ... disconnecting, got an exception, print stacktrace");
        e.printStackTrace();
    }
}

From source file:it.govpay.core.utils.client.BasicClient.java

private byte[] send(boolean soap, String azione, JAXBElement<?> body, Object header, boolean isAzioneInUrl)
        throws ClientException {

    // Creazione Connessione
    int responseCode;
    HttpURLConnection connection = null;
    byte[] msg = null;
    GpContext ctx = GpThreadLocal.get();
    String urlString = url.toExternalForm();
    if (isAzioneInUrl) {
        if (!urlString.endsWith("/"))
            urlString = urlString.concat("/");
        try {//from  www  .j a  v  a  2  s .  c  om
            url = new URL(urlString.concat(azione));
        } catch (MalformedURLException e) {
            throw new ClientException("Url di connessione malformata: " + urlString.concat(azione), e);
        }
    }

    try {
        Message requestMsg = new Message();
        requestMsg.setType(MessageType.REQUEST_OUT);

        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        if (soap) {
            connection.setRequestProperty("SOAPAction", "\"" + azione + "\"");
            requestMsg.addHeader(new Property("SOAPAction", "\"" + azione + "\""));
        }
        requestMsg.setContentType("text/xml");
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setRequestMethod("POST");

        // Imposta Contesto SSL se attivo
        if (sslContext != null) {
            HttpsURLConnection httpsConn = (HttpsURLConnection) connection;
            httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
            HostNameVerifierDisabled disabilitato = new HostNameVerifierDisabled();
            httpsConn.setHostnameVerifier(disabilitato);
        }

        // Imposta l'autenticazione HTTP Basic se attiva
        if (ishttpBasicEnabled) {
            Base64 base = new Base64();
            String encoding = new String(base.encode((httpBasicUser + ":" + httpBasicPassword).getBytes()));
            connection.setRequestProperty("Authorization", "Basic " + encoding);
            requestMsg.addHeader(new Property("Authorization", "Basic " + encoding));
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (soap) {
            SOAPUtils.writeMessage(body, header, baos);
        } else {
            JaxbUtils.marshal(body, baos);
        }

        ctx.getIntegrationCtx().setMsg(baos.toByteArray());
        invokeOutHandlers();

        if (log.getLevel().isMoreSpecificThan(Level.TRACE)) {
            StringBuffer sb = new StringBuffer();
            for (String key : connection.getRequestProperties().keySet()) {
                sb.append("\n\t" + key + ": " + connection.getRequestProperties().get(key));
            }
            sb.append("\n" + new String(ctx.getIntegrationCtx().getMsg()));
            log.trace(sb.toString());
        }

        requestMsg.setContent(ctx.getIntegrationCtx().getMsg());

        ctx.getContext().getRequest().setOutDate(new Date());
        ctx.getContext().getRequest().setOutSize(Long.valueOf(ctx.getIntegrationCtx().getMsg().length));
        ctx.log(requestMsg);

        connection.getOutputStream().write(ctx.getIntegrationCtx().getMsg());

    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        responseCode = connection.getResponseCode();
        ctx.getTransaction().getServer().setTransportCode(Integer.toString(responseCode));

    } catch (Exception e) {
        throw new ClientException(e);
    }

    Message responseMsg = new Message();
    responseMsg.setType(MessageType.RESPONSE_IN);

    for (String key : connection.getHeaderFields().keySet()) {
        if (connection.getHeaderFields().get(key) != null) {
            if (key == null)
                responseMsg
                        .addHeader(new Property("Status-line", connection.getHeaderFields().get(key).get(0)));
            else if (connection.getHeaderFields().get(key).size() == 1)
                responseMsg.addHeader(new Property(key, connection.getHeaderFields().get(key).get(0)));
            else
                responseMsg.addHeader(
                        new Property(key, ArrayUtils.toString(connection.getHeaderFields().get(key))));
        }
    }

    try {
        if (responseCode < 300) {
            try {
                if (connection.getInputStream() == null) {
                    return null;
                }
                msg = connection.getInputStream() != null ? IOUtils.toByteArray(connection.getInputStream())
                        : new byte[] {};
                if (msg.length > 0)
                    responseMsg.setContent(msg);
                return msg;
            } catch (Exception e) {
                throw new ClientException("Messaggio di risposta non valido", e);
            }
        } else {
            try {
                msg = connection.getErrorStream() != null ? IOUtils.toByteArray(connection.getErrorStream())
                        : new byte[] {};
                responseMsg.setContent(msg);
            } catch (IOException e) {
                msg = ("Impossibile serializzare l'ErrorStream della risposta: " + e).getBytes();
            } finally {
                log.warn("Errore nell'invocazione del Nodo dei Pagamenti [HTTP Response Code " + responseCode
                        + "]\nRisposta: " + new String(msg));
            }

            throw new ClientException("Ricevuto [HTTP " + responseCode + "]");
        }
    } finally {
        if (responseMsg != null) {
            ctx.getContext().getResponse().setInDate(new Date());
            ctx.getContext().getResponse().setInSize((long) responseMsg.getContent().length);
            ctx.log(responseMsg);
        }

        if (log.getLevel().isMoreSpecificThan(Level.TRACE) && connection != null
                && connection.getHeaderFields() != null) {
            StringBuffer sb = new StringBuffer();
            for (String key : connection.getHeaderFields().keySet()) {
                sb.append("\n\t" + key + ": " + connection.getHeaderField(key));
            }
            sb.append("\n" + new String(msg));
            log.trace(sb.toString());
        }
    }

}