Example usage for java.net HttpURLConnection getErrorStream

List of usage examples for java.net HttpURLConnection getErrorStream

Introduction

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

Prototype

public InputStream getErrorStream() 

Source Link

Document

Returns the error stream if the connection failed but the server sent useful data nonetheless.

Usage

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

/**
 * {@inheritDoc}// w ww .jav  a2  s.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);
    }
}

From source file:com.wareninja.android.opensource.mongolab_sdk.common.WebService.java

public String webPost(String methodName, Bundle params) throws MalformedURLException, IOException {

    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";
    OutputStream os;/*from w w w  .  ja va 2  s . c  o  m*/

    ret = null;

    String postUrl = webServiceUrl + methodName;

    if (AppContext.isDebugMode())
        Log.d(TAG, "POST URL: " + postUrl);
    HttpURLConnection conn = (HttpURLConnection) new URL(postUrl).openConnection();

    /*for (RequestHeader header : headers) {
       if (header != null) {
    conn.setRequestProperty(header.getKey(), header.getValue());
            
    if (AppContext.isDebugMode()) {
       Log.d(TAG, String.format("httpDelete.setHeader(%s, %s)", header.getKey(), header.getValue()) );
    }
       }
    }*/

    //if ( TextUtils.isEmpty(conn.getRequestProperty("User-Agent")) ) {
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " WareNinjaAndroidSDK"//"com.wareninja.android.mayormonster"//CommonUtils.getMyUserAgent(mContext)//
    );
    //}

    Bundle dataparams = new Bundle();
    for (String key : params.keySet()) {

        byte[] byteArr = null;
        try {
            byteArr = (byte[]) params.get(key);
        } catch (Exception ex1) {
        }
        if (byteArr != null)
            dataparams.putByteArray(key, byteArr);
    }

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Connection", "Keep-Alive");
    appendRequestHeaders(conn, headers);
    conn.connect();
    os = new BufferedOutputStream(conn.getOutputStream());

    os.write(("--" + strBoundary + endLine).getBytes());
    os.write((CommonUtils.encodePostBody(params, strBoundary)).getBytes());
    os.write((endLine + "--" + strBoundary + endLine).getBytes());

    if (!dataparams.isEmpty()) {

        for (String key : dataparams.keySet()) {
            os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
            os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
            os.write(dataparams.getByteArray(key));
            os.write((endLine + "--" + strBoundary + endLine).getBytes());

        }
    }
    os.flush();

    String response = "";
    try {
        response = CommonUtils.read(conn.getInputStream());
        //mHttpResponseCode = conn.getResponseCode();
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = CommonUtils.read(conn.getErrorStream());
    }
    if (AppContext.isDebugMode())
        Log.d(TAG, "POST response: " + response);

    return response;
}

From source file:edu.ku.brc.specify.web.HttpLargeFileTransfer.java

/**
 * @param fileName//from  w  w w. ja va  2  s.c o  m
 * @param urlStr
 * @param isSiteFile
 * @param propChgListener
 */
public void transferFile(final String fileName, final String urlStr, final boolean isSiteFile,
        final PropertyChangeListener propChgListener) {

    final String prgName = HttpLargeFileTransfer.class.toString();

    final File file = new File(fileName);
    if (file.exists()) {
        final long fileSize = file.length();
        if (fileSize > 0) {
            SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
                protected String errorMsg = null;
                protected FileInputStream fis = null;
                protected OutputStream fos = null;
                protected int nChunks = 0;

                /* (non-Javadoc)
                 * @see javax.swing.SwingWorker#doInBackground()
                 */
                @Override
                protected Integer doInBackground() throws Exception {
                    try {
                        Thread.sleep(100);
                        fis = new FileInputStream(file);

                        nChunks = (int) (fileSize / MAX_CHUNK_SIZE);
                        if (fileSize % MAX_CHUNK_SIZE > 0) {
                            nChunks++;
                        }

                        byte[] buf = new byte[BUFFER_SIZE];
                        long bytesRemaining = fileSize;

                        String clientID = String.valueOf((long) (Long.MIN_VALUE * Math.random()));

                        URL url = new URL(urlStr);

                        UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks);

                        for (int i = 0; i < nChunks; i++) {
                            firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i);
                            if (i == nChunks - 1) {
                                Thread.sleep(500);
                                int x = 0;
                                x++;
                            }

                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            conn.setRequestMethod("PUT");
                            conn.setDoOutput(true);
                            conn.setDoInput(true);
                            conn.setUseCaches(false);

                            int chunkSize = (int) ((bytesRemaining > MAX_CHUNK_SIZE) ? MAX_CHUNK_SIZE
                                    : bytesRemaining);
                            bytesRemaining -= chunkSize;

                            conn.setRequestProperty("Content-Type", "application/octet-stream");
                            conn.setRequestProperty("Content-Length", String.valueOf(chunkSize));

                            conn.setRequestProperty(CLIENT_ID_HEADER, clientID);
                            conn.setRequestProperty(FILE_NAME_HEADER, fileName);
                            conn.setRequestProperty(FILE_CHUNK_COUNT_HEADER, String.valueOf(nChunks));
                            conn.setRequestProperty(FILE_CHUNK_HEADER, String.valueOf(i));
                            conn.setRequestProperty(SERVICE_NUMBER, "10");
                            conn.setRequestProperty(IS_SITE_FILE, Boolean.toString(isSiteFile));

                            fos = conn.getOutputStream();

                            //UIRegistry.getStatusBar().setProgressRange(prgName, 0, (int)((double)chunkSize / BUFFER_SIZE));
                            int cnt = 0;
                            int bytesRead = 0;
                            while (bytesRead < chunkSize) {
                                int read = fis.read(buf);
                                if (read == -1) {
                                    break;

                                } else if (read > 0) {
                                    bytesRead += read;
                                    fos.write(buf, 0, read);
                                }
                                cnt++;
                                //firePropertyChange(prgName, cnt-1, cnt);
                            }
                            fos.close();

                            if (conn.getResponseCode() != HttpServletResponse.SC_OK) {
                                System.err.println(
                                        conn.getResponseMessage() + " " + conn.getResponseCode() + " ");
                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(conn.getErrorStream()));
                                String line = null;
                                StringBuilder sb = new StringBuilder();
                                while ((line = in.readLine()) != null) {
                                    sb.append(line);
                                    sb.append("\n");
                                }
                                System.out.println(sb.toString());
                                in.close();

                            } else {
                                System.err.println("OK");
                            }
                            //UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks);
                            firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i);
                        }

                    } catch (IOException ex) {
                        errorMsg = ex.toString();
                    }

                    //firePropertyChange(prgName, 0, 100);
                    return null;
                }

                @Override
                protected void done() {
                    super.done();

                    UIRegistry.getStatusBar().setProgressDone(prgName);

                    UIRegistry.clearSimpleGlassPaneMsg();

                    if (StringUtils.isNotEmpty(errorMsg)) {
                        UIRegistry.showError(errorMsg);
                    }

                    if (propChgListener != null) {
                        propChgListener.propertyChange(
                                new PropertyChangeEvent(HttpLargeFileTransfer.this, "Done", 0, 1));
                    }
                }
            };

            final JStatusBar statusBar = UIRegistry.getStatusBar();
            statusBar.setIndeterminate(HttpLargeFileTransfer.class.toString(), true);

            UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("Transmitting..."), 24);

            backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(final PropertyChangeEvent evt) {
                    System.out.println(evt.getPropertyName() + "  " + evt.getNewValue());
                    if (prgName.equals(evt.getPropertyName())) {
                        Integer value = (Integer) evt.getNewValue();
                        if (value == Integer.MAX_VALUE) {
                            statusBar.setIndeterminate(prgName, true);
                            UIRegistry.writeSimpleGlassPaneMsg(
                                    getLocalizedMessage("Transfering data into the database."), 24);

                        } else {
                            statusBar.setValue(prgName, value);
                        }
                    }
                }
            });
            backupWorker.execute();

        } else {
            // file doesn't exist
        }
    } else {
        // file doesn't exist
    }
}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

private String uploadMetaData(final Activity activity, final Handler handler, String filePath, String title,
        String description, boolean retry) throws IOException {
    String uploadUrl = INITIAL_UPLOAD_URL;

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);//from w ww  .j a v a  2s .c  o  m
    urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
    // urlConnection.setRequestProperty("Content-Length", newValue);
    urlConnection.setRequestProperty("Slug", filePath);
    String atomData = null;

    String category = DEFAULT_VIDEO_CATEGORY;
    this.tags = DEFAULT_VIDEO_TAGS;

    String template = readFile(activity, R.raw.gdata).toString();

    // Workarounds for corner cases. Youtube doesnt like empty titles
    if (title == null || title.length() == 0) {
        title = "Untitled";
    }
    if (description == null || description.length() == 0) {
        description = "No description";
    }

    atomData = String.format(template, title, description, category, this.tags);

    OutputStreamWriter outStreamWriter = null;
    int responseCode = -1;

    try {
        outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
        outStreamWriter.write(atomData);
        outStreamWriter.close();

        /*
         * urlConnection.connect(); InputStream is =
         * urlConnection.getInputStream(); BufferedReader in = new
         * BufferedReader(new InputStreamReader(is)); String inputLine;
         * 
         * while ((inputLine = in.readLine()) != null) {
         * Log.d(TAG,inputLine); } in.close();
         */

        responseCode = urlConnection.getResponseCode();

        // ERROR LOGGING
        InputStream is = urlConnection.getErrorStream();
        if (is != null) {
            Log.e(TAG, " Error stream from Youtube available!");
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                Log.d(TAG, inputLine);
            }
            in.close();

            Map<String, List<String>> hfs = urlConnection.getHeaderFields();
            for (Entry<String, List<String>> hf : hfs.entrySet()) {
                Log.d(TAG, " entry : " + hf.getKey());
                List<String> vals = hf.getValue();
                for (String s : vals) {
                    Log.d(TAG, "vals:" + s);
                }
            }
        }

    } catch (IOException e) {
        //
        // Catch IO Exceptions here, like UnknownHostException, so we can
        // detect network failures, and send a notification
        //
        Log.d(TAG, " Error occured in uploadMetaData! ");
        e.printStackTrace();
        responseCode = -1;
        outStreamWriter = null;

        // Use the handler to execute a Runnable on the
        // main thread in order to have access to the
        // UI elements.
        handler.postDelayed(new Runnable() {
            public void run() {
                // Update UI

                // Indicate back to calling activity the result!
                // update uploadInProgress state also.

                ((SSCXferActivity) activity).finishedUploading(false);
                ((SSCXferActivity) activity)
                        .createNotification(res.getString(R.string.upload_to_youtube_host_failed_));

            }
        }, 0);

        // forward it on!
        throw e;
    }

    if (responseCode < 200 || responseCode >= 300) {
        // The response code is 40X
        if ((responseCode + "").startsWith("4") && retry) {
            Log.d(TAG, "retrying to fetch auth token for " + youTubeName);
            this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken);
            // Try again with fresh token
            return uploadMetaData(activity, handler, filePath, title, description, false);
        } else {

            // Probably not authorised!

            // Need to setup a Youtube account.

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((SSCXferActivity) activity).finishedUploading(false);
                    ((SSCXferActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_youtube_host_failed_));

                }
            }, 0);

            throw new IOException(String.format("response code='%s' (code %d)" + " for %s",
                    urlConnection.getResponseMessage(), responseCode, urlConnection.getURL()));

        }
    }

    return urlConnection.getHeaderField("Location");
}

From source file:com.etalio.android.EtalioBase.java

protected String multipartRequest(String urlTo, InputStream fileInputStream, String filefield, String filename)
        throws ParseException, IOException, EtalioHttpException {
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;

    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    String lineEnd = "\r\n";

    String result = "";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    try {//from  ww w .  j a va 2s  .  c  om
        URL url = new URL(urlTo);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");

        connection.setRequestProperty("Authorization", " Bearer " + getEtalioToken().getAccessToken());
        connection.setRequestProperty("User-Agent", getEtalioUserAgent());
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\""
                + filename + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: " + MimeTypeUtil.getMimeType(filename) + lineEnd);
        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
        outputStream.writeBytes(lineEnd);

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

        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);

        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        inputStream = connection.getInputStream();

        if (connection.getResponseCode() > 300) {
            result = convertStreamToString(connection.getErrorStream());
        } else {
            result = this.convertStreamToString(inputStream);
        }

        fileInputStream.close();
        inputStream.close();
        outputStream.flush();
        outputStream.close();

        return result;
    } catch (Exception e) {
        throw new EtalioHttpException(connection.getResponseCode(), connection.getResponseMessage(),
                e.getMessage());
    }
}

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java

public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri,
        String servletPath, String proxyPath) throws ServletException, IOException {
    //System.out.println("LOAD "+uri); 
    //System.out.println("LOAD "+proxyPath);

    if ("CONNECT".equalsIgnoreCase(request.getMethod())) {
        handleConnect(request, response);

    } else {//  www .j  av  a 2 s . c o m
        URL url = new URL(uri);

        URLConnection connection = url.openConnection();
        connection.setAllowUserInteraction(false);

        // Set method
        HttpURLConnection http = null;
        if (connection instanceof HttpURLConnection) {
            http = (HttpURLConnection) connection;
            http.setRequestMethod(request.getMethod());
            http.setInstanceFollowRedirects(false);
        }

        // check connection header
        String connectionHdr = request.getHeader("Connection");
        if (connectionHdr != null) {
            connectionHdr = connectionHdr.toLowerCase();
            if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
                connectionHdr = null;
        }

        // copy headers
        boolean xForwardedFor = false;
        boolean hasContent = false;
        Enumeration enm = request.getHeaderNames();
        while (enm.hasMoreElements()) {
            // TODO could be better than this!
            String hdr = (String) enm.nextElement();
            String lhdr = hdr.toLowerCase();

            if (_DontProxyHeaders.contains(lhdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
                continue;

            if ("content-type".equals(lhdr))
                hasContent = true;

            Enumeration vals = request.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    connection.addRequestProperty(hdr, val);
                    xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
                }
            }
        }

        // Proxy headers
        connection.setRequestProperty("Via", "1.1 (jetty)");
        if (!xForwardedFor)
            connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr());

        // a little bit of cache control
        String cache_control = request.getHeader("Cache-Control");
        if (cache_control != null
                && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
            connection.setUseCaches(false);

        // customize Connection

        try {
            connection.setDoInput(true);

            // do input thang!
            InputStream in = request.getInputStream();
            if (hasContent) {
                connection.setDoOutput(true);
                IOUtils.copy(in, connection.getOutputStream());
            }

            // Connect
            connection.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        InputStream proxy_in = null;

        // handler status codes etc.
        int code = 500;
        if (http != null) {
            proxy_in = http.getErrorStream();

            code = http.getResponseCode();
            response.setStatus(code, http.getResponseMessage());
        }

        if (proxy_in == null) {
            try {
                proxy_in = connection.getInputStream();
            } catch (Exception e) {
                e.printStackTrace();
                proxy_in = http.getErrorStream();
            }
        }

        // clear response defaults.
        response.setHeader("Date", null);
        response.setHeader("Server", null);

        // set response headers
        int h = 0;
        String hdr = connection.getHeaderFieldKey(h);
        String val = connection.getHeaderField(h);
        while (hdr != null || val != null) {
            String lhdr = hdr != null ? hdr.toLowerCase() : null;
            if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) {
                if (hdr.equalsIgnoreCase("Location")) {
                    val = Rewriter.translateCleanUrl(val, servletPath, proxyPath);
                }
                response.addHeader(hdr, val);

            }

            h++;
            hdr = connection.getHeaderFieldKey(h);
            val = connection.getHeaderField(h);

        }

        boolean isGzipped = connection.getContentEncoding() != null
                && connection.getContentEncoding().contains("gzip");
        response.addHeader("Via", "1.1 (jetty)");
        // boolean process = connection.getContentType() == null
        // || connection.getContentType().isEmpty()
        // || connection.getContentType().contains("html");
        boolean process = connection.getContentType() != null && connection.getContentType().contains("text");
        if (proxy_in != null) {
            if (!process) {
                IOUtils.copy(proxy_in, response.getOutputStream());
                proxy_in.close();
            } else {
                InputStream in;
                if (isGzipped && proxy_in != null && proxy_in.available() > 0) {
                    in = new GZIPInputStream(proxy_in);
                } else {
                    in = proxy_in;
                }
                ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream();
                IOUtils.copy(in, byteArrOS);
                in.close();
                if (in != proxy_in)
                    proxy_in.close();
                String charset = response.getCharacterEncoding();
                if (charset == null || charset.isEmpty()) {
                    charset = "ISO-8859-1";
                }
                String originalContent = new String(byteArrOS.toByteArray(), charset);
                byteArrOS.close();
                return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped);
            }
        }

    }
    return null;
}

From source file:com.aptana.jira.core.JiraManager.java

/**
 * Creates a JIRA ticket.// w w  w.  j a  v  a 2s.com
 * 
 * @param type
 *            the issue type (bug, feature, or improvement)
 * @param priority
 *            the issue's priority
 * @param severity
 *            the issue's severity (Blocker, Major, Minor, Trivial, None)
 * @param summary
 *            the summary of the ticket
 * @param description
 *            the description of the ticket
 * @return the JIRA issue created
 * @throws JiraException
 * @throws IOException
 */
public JiraIssue createIssue(JiraIssueType type, JiraIssueSeverity severity, String summary, String description)
        throws JiraException, IOException {
    if (user == null) {
        throw new JiraException(Messages.JiraManager_ERR_NotLoggedIn);
    }

    HttpURLConnection connection = null;
    try {
        connection = createConnection(getCreateIssueURL(), user.getUsername(), user.getPassword());
        connection.setRequestMethod("POST"); //$NON-NLS-1$
        connection.setDoOutput(true);
        String severityJSON;
        String versionString;
        if ((TITANIUM_COMMUNITY.equals(projectKey) && type == JiraIssueType.IMPROVEMENT)
                || (!TITANIUM_COMMUNITY.equals(projectKey) && type != JiraIssueType.BUG)) {
            // Improvements in TC don't get Severities, nor do Story or Improvements in Aptana Studio!
            severityJSON = StringUtil.EMPTY;
        } else {
            severityJSON = severity.getParameterValue() + ",\n"; //$NON-NLS-1$
        }

        // If we're submitting against TC, we can't do version, we need to stuff that into the Environment
        if (TITANIUM_COMMUNITY.equals(projectKey)) {
            versionString = MessageFormat.format("\"{0}\": \"{1}\"", PARAM_ENVIRONMENT, getProjectVersion()); //$NON-NLS-1$
        } else {
            versionString = "\"" + PARAM_VERSION + "\": [{\"name\": \"" + getProjectVersion() + "\"}]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }
        // @formatter:off
        String data = "{\n" + //$NON-NLS-1$
                "    \"fields\": {\n" + //$NON-NLS-1$
                "       \"project\":\n" + //$NON-NLS-1$
                "       { \n" + //$NON-NLS-1$
                "          \"key\": \"" + projectKey + "\"\n" + //$NON-NLS-1$ //$NON-NLS-2$
                "       },\n" + //$NON-NLS-1$
                "       \"summary\": \"" + summary.replaceAll("\"", "'") + "\",\n" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                "       \"description\": \"" //$NON-NLS-1$
                + description.replaceAll("\"", "'").replaceAll("\n", Matcher.quoteReplacement("\\n")) + "\",\n" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$//$NON-NLS-5$
                + "       \"issuetype\": {\n" + "          \"name\": \"" + type.getParameterValue(projectKey) + "\"\n" + //$NON-NLS-3$
                "       },\n" + //$NON-NLS-1$
                severityJSON + "       " + versionString + "\n" + //$NON-NLS-1$ //$NON-NLS-2$
                "   }\n" + //$NON-NLS-1$
                "}"; //$NON-NLS-1$
        // @formatter:on

        OutputStream out = connection.getOutputStream();
        IOUtil.write(out, data);
        out.close();

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
            String output = IOUtil.read(connection.getInputStream());
            return createIssueFromJSON(output);
        }
        // failed to create the ticket
        // TODO Parse the response as JSON!
        throw new JiraException(IOUtil.read(connection.getErrorStream()));
    } catch (JiraException je) {
        throw je;
    } catch (Exception e) {
        throw new JiraException(e.getMessage(), e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java

private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri,
        String postBody, StoredFile storedFile) {
    Log.d("Performing multipart request to %s", uri);

    ApptentiveHttpResponse ret = new ApptentiveHttpResponse();

    if (storedFile == null) {
        Log.e("StoredFile is null. Unable to send.");
        return ret;
    }/*from   w ww  .  ja va  2s.c om*/

    int bytesRead;
    int bufferSize = 4096;
    byte[] buffer;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = UUID.randomUUID().toString();

    HttpURLConnection connection;
    DataOutputStream os = null;
    InputStream is = null;

    try {
        is = context.openFileInput(storedFile.getLocalFilePath());

        // Set up the request.
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT);
        connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT);
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        connection.setRequestProperty("Authorization", "OAuth " + oauthToken);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("X-API-Version", API_VERSION);
        connection.setRequestProperty("User-Agent", getUserAgentString());

        StringBuilder requestText = new StringBuilder();

        // Write form data
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd);
        requestText.append("Content-Type: text/plain").append(lineEnd);
        requestText.append(lineEnd);
        requestText.append(postBody);
        requestText.append(lineEnd);

        // Write file attributes.
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"",
                storedFile.getFileName())).append(lineEnd);
        requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd);
        requestText.append(lineEnd);

        Log.d("Post body: " + requestText);

        // Open an output stream.
        os = new DataOutputStream(connection.getOutputStream());

        // Write the text so far.
        os.writeBytes(requestText.toString());

        try {
            // Write the actual file.
            buffer = new byte[bufferSize];
            while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            Log.d("Error writing file bytes to HTTP connection.", e);
            ret.setBadPayload(true);
            throw e;
        }

        os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        os.close();

        ret.setCode(connection.getResponseCode());
        ret.setReason(connection.getResponseMessage());

        // TODO: These streams may not be ready to read now. Put this in a new thread.
        // Read the normal response.
        InputStream nis = null;
        ByteArrayOutputStream nbaos = null;
        try {
            Log.d("Sending file: " + storedFile.getLocalFilePath());
            nis = connection.getInputStream();
            nbaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) {
                nbaos.write(eBuf, 0, eRead);
            }
            ret.setContent(nbaos.toString());
        } catch (IOException e) {
            Log.w("Can't read return stream.", e);
        } finally {
            Util.ensureClosed(nis);
            Util.ensureClosed(nbaos);
        }

        // Read the error response.
        InputStream eis = null;
        ByteArrayOutputStream ebaos = null;
        try {
            eis = connection.getErrorStream();
            ebaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) {
                ebaos.write(eBuf, 0, eRead);
            }
            if (ebaos.size() > 0) {
                ret.setContent(ebaos.toString());
            }
        } catch (IOException e) {
            Log.w("Can't read error stream.", e);
        } finally {
            Util.ensureClosed(eis);
            Util.ensureClosed(ebaos);
        }

        Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + "");
        Log.v(ret.getContent());
    } catch (FileNotFoundException e) {
        Log.e("Error getting file to upload.", e);
    } catch (MalformedURLException e) {
        Log.e("Error constructing url for file upload.", e);
    } catch (SocketTimeoutException e) {
        Log.w("Timeout communicating with server.");
    } catch (IOException e) {
        Log.e("Error executing file upload.", e);
    } finally {
        Util.ensureClosed(is);
        Util.ensureClosed(os);
    }
    return ret;
}

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {
    AQUtility.debug("multipart", url);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;// w w w  .  j  av a  2 s  . co  m
    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();
    conn.setInstanceFollowRedirects(false);
    conn.setConnectTimeout(NET_TIMEOUT * 4);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);
    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }
    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }
    if (ah != null) {
        ah.applyToken(this, conn);
    }
    dos = new DataOutputStream(conn.getOutputStream());
    Object o = null;
    if (progress != null) {
        o = progress.get();
    }
    Progress p = null;
    if (o != null) {
        p = new Progress(o);
    }
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        writeObject(dos, entry.getKey(), entry.getValue(), p);
    }
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();
    conn.connect();
    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();
    byte[] data = null;
    String encoding = conn.getContentEncoding();
    String error = null;
    if ((code < 200) || (code >= 300)) {
        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");
        AQUtility.debug("error", error);
    } else {
        data = toData(encoding, conn.getInputStream());
    }
    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }
    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);
}