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:dk.itst.oiosaml.sp.service.util.HttpSOAPClient.java

public Envelope wsCall(String location, String username, String password, boolean ignoreCertPath, String xml,
        String soapAction) throws IOException, SOAPException {
    URI serviceLocation;/*from   w  w  w .  j av  a  2  s .  c o  m*/
    try {
        serviceLocation = new URI(location);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid uri for artifact resolve: " + location);
    }
    if (log.isDebugEnabled())
        log.debug("serviceLocation..:" + serviceLocation);
    if (log.isDebugEnabled())
        log.debug("SOAP Request: " + xml);

    HttpURLConnection c = (HttpURLConnection) serviceLocation.toURL().openConnection();
    if (c instanceof HttpsURLConnection) {
        HttpsURLConnection sc = (HttpsURLConnection) c;

        if (ignoreCertPath) {
            sc.setSSLSocketFactory(new DummySSLSocketFactory());
            sc.setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
    }
    c.setAllowUserInteraction(false);
    c.setDoInput(true);
    c.setDoOutput(true);
    c.setFixedLengthStreamingMode(xml.getBytes("UTF-8").length);
    c.setRequestMethod("POST");
    c.setReadTimeout(20000);
    c.setConnectTimeout(30000);

    addContentTypeHeader(xml, c);
    c.addRequestProperty("SOAPAction", "\"" + (soapAction == null ? "" : soapAction) + "\"");

    if (username != null && password != null) {
        c.addRequestProperty("Authorization",
                "Basic " + Base64.encodeBytes((username + ":" + password).getBytes(), Base64.DONT_BREAK_LINES));
    }
    OutputStream outputStream = c.getOutputStream();
    IOUtils.write(xml, outputStream, "UTF-8");
    outputStream.flush();
    outputStream.close();

    if (c.getResponseCode() == 200) {
        InputStream inputStream = c.getInputStream();
        String result = IOUtils.toString(inputStream, "UTF-8");
        inputStream.close();

        if (log.isDebugEnabled())
            log.debug("Server SOAP response: " + result);
        XMLObject res = SAMLUtil.unmarshallElementFromString(result);

        Envelope envelope = (Envelope) res;
        if (SAMLUtil.getFirstElement(envelope.getBody(), Fault.class) != null) {
            log.warn(
                    "Result has soap11:Fault, but server returned 200 OK. Treating as error, please fix the server");
            throw new SOAPException(c.getResponseCode(), result);
        }
        return envelope;
    } else {
        log.debug("Response code: " + c.getResponseCode());

        InputStream inputStream = c.getErrorStream();
        String result = IOUtils.toString(inputStream, "UTF-8");
        inputStream.close();
        if (log.isDebugEnabled())
            log.debug("Server SOAP fault: " + result);

        throw new SOAPException(c.getResponseCode(), result);
    }
}

From source file:ch.cyberduck.core.gdocs.GDSession.java

@Override
protected void connect() throws IOException {
    if (this.isConnected()) {
        return;//  w  w w . j  a  v a 2  s.c  o  m
    }
    this.fireConnectionWillOpenEvent();

    GoogleGDataRequest.Factory requestFactory = new GoogleGDataRequest.Factory();
    requestFactory.setConnectionSource(new HttpUrlConnectionSource() {
        public HttpURLConnection openConnection(URL url) throws IOException {
            return getConnection(url);
        }
    });
    GoogleAuthTokenFactory authFactory = new GoogleAuthTokenFactory(DocsService.DOCS_SERVICE,
            this.getUserAgent(), host.getProtocol().getScheme(), "www.google.com", client) {

        @Override
        public String getAuthToken(String username, String password, String captchaToken, String captchaAnswer,
                String serviceName, String applicationName, ClientLoginAccountType accountType)
                throws AuthenticationException {

            Map<String, String> params = new HashMap<String, String>();
            params.put("Email", username);
            params.put("Passwd", password);
            params.put("source", applicationName);
            params.put("service", serviceName);
            params.put("accountType", accountType.getValue());

            if (captchaToken != null) {
                params.put("logintoken", captchaToken);
            }
            if (captchaAnswer != null) {
                params.put("logincaptcha", captchaAnswer);
            }
            String postOutput;
            try {
                URL url = new URL(
                        host.getProtocol().getScheme() + "://" + "www.google.com" + GOOGLE_LOGIN_PATH);
                postOutput = request(url, params);
            } catch (IOException e) {
                AuthenticationException ae = new AuthenticationException(
                        Locale.localizedString("Connection failed", "Error"));
                ae.initCause(e);
                throw ae;
            }

            // Parse the output
            Map<String, String> tokenPairs = StringUtil.string2Map(postOutput.trim(), "\n", "=", true);
            String token = tokenPairs.get("Auth");
            if (token == null) {
                throw getAuthException(tokenPairs);
            }
            return token;
        }

        /**
         * Returns the respective {@code AuthenticationException} given the return
         * values from the login URI handler.
         *
         * @param pairs name/value pairs returned as a result of a bad authentication
         * @return the respective {@code AuthenticationException} for the given error
         */
        private AuthenticationException getAuthException(Map<String, String> pairs) {

            String errorName = pairs.get("Error");

            if ("BadAuthentication".equals(errorName)) {
                return new GoogleService.InvalidCredentialsException("Invalid credentials");

            } else if ("AccountDeleted".equals(errorName)) {
                return new GoogleService.AccountDeletedException("Account deleted");

            } else if ("AccountDisabled".equals(errorName)) {
                return new GoogleService.AccountDisabledException("Account disabled");

            } else if ("NotVerified".equals(errorName)) {
                return new GoogleService.NotVerifiedException("Not verified");

            } else if ("TermsNotAgreed".equals(errorName)) {
                return new GoogleService.TermsNotAgreedException("Terms not agreed");

            } else if ("ServiceUnavailable".equals(errorName)) {
                return new GoogleService.ServiceUnavailableException("Service unavailable");

            } else if ("CaptchaRequired".equals(errorName)) {

                String captchaPath = pairs.get("CaptchaUrl");
                StringBuilder captchaUrl = new StringBuilder();
                captchaUrl.append(host.getProtocol().getScheme()).append("://").append("www.google.com")
                        .append(GOOGLE_ACCOUNTS_PATH).append('/').append(captchaPath);
                return new GoogleService.CaptchaRequiredException("Captcha required", captchaUrl.toString(),
                        pairs.get("CaptchaToken"));

            } else {
                return new AuthenticationException("Error authenticating " + "(check service name)");
            }
        }

        /**
         * Makes a HTTP POST request to the provided {@code url} given the
         * provided {@code parameters}.  It returns the output from the POST
         * handler as a String object.
         *
         * @param url the URL to post the request
         * @param parameters the parameters to post to the handler
         * @return the output from the handler
         * @throws IOException if an I/O exception occurs while creating, writing,
         *                     or reading the request
         */
        private String request(URL url, Map<String, String> parameters) throws IOException {

            // Open connection
            HttpURLConnection urlConnection = getConnection(url);

            // Set properties of the connection
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // Form the POST parameters
            StringBuilder content = new StringBuilder();
            boolean first = true;
            for (Map.Entry<String, String> parameter : parameters.entrySet()) {
                if (!first) {
                    content.append("&");
                }
                content.append(CharEscapers.uriEscaper().escape(parameter.getKey())).append("=");
                content.append(CharEscapers.uriEscaper().escape(parameter.getValue()));
                first = false;
            }

            OutputStream outputStream = null;
            try {
                outputStream = urlConnection.getOutputStream();
                outputStream.write(content.toString().getBytes("utf-8"));
                outputStream.flush();
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }

            // Retrieve the output
            InputStream inputStream = null;
            StringBuilder outputBuilder = new StringBuilder();
            try {
                int responseCode = urlConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    inputStream = urlConnection.getInputStream();
                } else {
                    inputStream = urlConnection.getErrorStream();
                }

                String string;
                if (inputStream != null) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    while (null != (string = reader.readLine())) {
                        outputBuilder.append(string).append('\n');
                    }
                }
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            return outputBuilder.toString();
        }
    };
    client = new DocsService(this.getUserAgent(), requestFactory, authFactory);
    client.setReadTimeout(this.timeout());
    client.setConnectTimeout(this.timeout());
    if (this.getHost().getProtocol().isSecure()) {
        client.useSsl();
    }

    if (!this.isConnected()) {
        throw new ConnectionCanceledException();
    }
    this.login();
    this.fireConnectionDidOpenEvent();
}

From source file:com.jamsuni.jamsunicodescan.MainActivity.java

public void testTTS(String msg) {

    String apiURL = "https://openapi.naver.com/v1/voice/tts.bin";

    BookInfo bookInfo = new BookInfo();

    try {/*  w  w  w . ja  v  a2s.co m*/
        String text = URLEncoder.encode(msg, "UTF-8");

        URL url = new URL(apiURL);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");

        con.setRequestProperty("X-Naver-Client-Id", clientId);
        con.setRequestProperty("X-Naver-Client-Secret", clientSecret);

        // post request
        String postParams = "speaker=mijin&speed=0&text=" + text;
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        BufferedReader br;
        if (responseCode == 200) { // ? 
            InputStream is = con.getInputStream();
            int read = 0;
            byte[] bytes = new byte[1024];
            // ? ? mp3 ? ?
            String tempname = Long.valueOf(new Date().getTime()).toString();
            File f = new File(Environment.getExternalStorageDirectory() + "/" + tempname + ".mp3");
            f.createNewFile();
            OutputStream outputStream = new FileOutputStream(f);
            while ((read = is.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
            is.close();
        } else { // ? ?
            br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
            System.out.println(response.toString());
        }

    } catch (Exception e) {
        System.out.println(e);
    }

    return;
}

From source file:fr.haploid.webservices.WebServicesTask.java

@Override
protected JSONObject doInBackground(Void... params) {
    try {/*from w  w  w.j  ava  2 s.  c om*/
        if (mSendCacheResult) {
            JSONObject cacheResultMessage = new JSONObject();
            cacheResultMessage.put(Cobalt.kJSType, Cobalt.JSTypePlugin);
            cacheResultMessage.put(Cobalt.kJSPluginName, JSPluginNameWebservices);

            JSONObject storedData = new JSONObject();
            storedData.put(kJSCallId, mCallId);
            cacheResultMessage.put(Cobalt.kJSData, storedData);

            int storageSize = WebServicesData.getCountItem();
            if (storageSize > 0) {
                if (mStorageKey != null) {
                    String storedValue = WebServicesPlugin.storedValueForKey(mStorageKey, mFragment);

                    if (storedValue != null) {
                        try {
                            storedData.put(Cobalt.kJSData, WebServicesPlugin
                                    .treatData(new JSONObject(storedValue), mProcessData, mFragment));

                            cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageResult);
                            //cacheResultMessage.put(Cobalt.kJSData, storedData);
                        } catch (JSONException exception) {
                            if (Cobalt.DEBUG) {
                                Log.e(WebServicesPlugin.TAG,
                                        TAG + " - doInBackground: value parsing failed for key " + mStorageKey
                                                + ". Value: " + storedValue);
                                exception.printStackTrace();
                            }

                            cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                            storedData.put(kJSText, JSTextUnknownError);
                        }
                    } else {
                        if (Cobalt.DEBUG)
                            Log.w(WebServicesPlugin.TAG,
                                    TAG + " - doInBackground: value not found in cache for key " + mStorageKey
                                            + ".");

                        cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                        storedData.put(kJSText, JSTextNotFound);
                    }
                } else {
                    cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                    storedData.put(kJSText, JSTextUnknownError);

                }
            } else {
                if (Cobalt.DEBUG)
                    Log.w(WebServicesPlugin.TAG, TAG + " - doInBackground: cache is empty.");

                cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                storedData.put(kJSText, JSTextEmpty);
            }
            cacheResultMessage.put(Cobalt.kJSData, storedData);

            mFragment.sendMessage(cacheResultMessage);
        }

        if (mUrl != null && mType != null) {
            // TODO: later, use Helper
            /*
            responseData = WebServicesHelper.downloadFromServer(data.getString(URL), data.getJSONObject(PARAMS), data.getString(TYPE));
            if (responseData != null) {
            responseHolder.put(TEXT, responseData.getResponseData());
            responseHolder.put(STATUS_CODE, responseData.getStatusCode());
            responseHolder.put(WS_SUCCESS, responseData.isSuccess());
            responseHolder.put(CALL_WS, true);
            }
            */

            Uri.Builder builder = new Uri.Builder();
            builder.encodedPath(mUrl);

            if (!mParams.equals("") && mType.equalsIgnoreCase(JSTypeGET))
                builder.encodedQuery(mParams);

            JSONObject response = new JSONObject();
            response.put(kJSSuccess, false);

            try {
                URL url = new URL(builder.build().toString());

                try {
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    if (mTimeout > 0)
                        urlConnection.setConnectTimeout(mTimeout);
                    urlConnection.setRequestMethod(mType);
                    urlConnection.setDoInput(true);

                    if (mHeaders != null) {
                        JSONArray names = mHeaders.names();

                        if (names != null) {
                            int length = names.length();

                            for (int i = 0; i < length; i++) {
                                String name = names.getString(i);
                                urlConnection.setRequestProperty(name, mHeaders.get(name).toString());
                            }
                        }
                    }

                    if (!mParams.equals("") && !mType.equalsIgnoreCase(JSTypeGET)) {
                        urlConnection.setDoOutput(true);

                        OutputStream outputStream = urlConnection.getOutputStream();
                        BufferedWriter writer = new BufferedWriter(
                                new OutputStreamWriter(outputStream, "UTF-8"));
                        writer.write(mParams);
                        writer.flush();
                        writer.close();
                        outputStream.close();
                    }

                    urlConnection.connect();

                    int responseCode = urlConnection.getResponseCode();
                    if (responseCode != -1) {
                        response.put(kJSStatusCode, responseCode);
                        if (responseCode < 400)
                            response.put(kJSSuccess, true);
                    }

                    try {
                        InputStream inputStream;
                        if (responseCode >= 400 && responseCode < 600)
                            inputStream = urlConnection.getErrorStream();
                        else
                            inputStream = urlConnection.getInputStream();

                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        StringBuffer buffer = new StringBuffer();
                        String line;

                        while ((line = reader.readLine()) != null) {
                            buffer.append(line).append("\n");
                        }
                        if (buffer.length() != 0)
                            response.put(kJSText, buffer.toString());
                    } catch (IOException exception) {
                        if (Cobalt.DEBUG) {
                            Log.i(WebServicesPlugin.TAG,
                                    TAG + " - doInBackground: no DATA returned by server.");
                            exception.printStackTrace();
                        }
                    }
                } catch (ProtocolException exception) {
                    if (Cobalt.DEBUG) {
                        Log.e(WebServicesPlugin.TAG,
                                TAG + " - doInBackground: not supported request method type " + mType);
                        exception.printStackTrace();
                    }
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
                return response;
            } catch (MalformedURLException exception) {
                if (Cobalt.DEBUG) {
                    Log.e(WebServicesPlugin.TAG,
                            TAG + " - doInBackground: malformed url " + builder.build().toString() + ".");
                    exception.printStackTrace();
                }
            }
        }
    } catch (JSONException exception) {
        exception.printStackTrace();
    }

    return null;
}

From source file:com.pocketsoap.salesforce.soap.ChatterClient.java

private String postSuspectsComment(String postId, Map<String, String> suspects, boolean retryOnInvalidSession)
        throws MalformedURLException, IOException, XMLStreamException, FactoryConfigurationError {
    URL instanceUrl = new URL(session.instanceServerUrl);
    URL url = new URL(instanceUrl.getProtocol(), instanceUrl.getHost(), instanceUrl.getPort(),
            "/services/data/v24.0/chatter/feed-items/" + postId + "/comments");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    try {//from  w w  w  .  j a  v a2  s. c  o m
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", "OAuth " + session.sessionId);

        final Comment comment = new Comment();
        final List<MessageSegment> messageSegments = comment.getBody().getMessageSegments();
        messageSegments.add(new TextMessageSegment("Suspects: "));

        Iterator<Entry<String, String>> it = suspects.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, String> ids = it.next();

            String sfdcId = ids.getValue();
            if (sfdcId != null) {
                //Convert the login to an SFDC ID
                sfdcId = UserService.getUserId(session, sfdcId);
            }

            if (sfdcId == null) { //not mapped
                messageSegments.add(new TextMessageSegment(ids.getKey()));
            } else {
                messageSegments.add(new MentionMessageSegment(sfdcId));
            }

            if (it.hasNext()) {
                messageSegments.add(new TextMessageSegment(", "));
            }
        }

        final OutputStream bodyStream = conn.getOutputStream();
        ObjectMapper mapper = new ObjectMapper();
        MappingJsonFactory jsonFactory = new MappingJsonFactory();
        JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(bodyStream);
        mapper.writeValue(jsonGenerator, comment);
        bodyStream.close();
        conn.getInputStream().close(); //Don't care about the response
    } catch (IOException e) {
        if (retryOnInvalidSession && conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            SessionCache.get().revoke(credentials);
            return postSuspectsComment(postId, suspects, false);
        }

        BufferedReader r = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        String error = "";
        String line;
        while ((line = r.readLine()) != null) {
            error += line + '\n';
        }
        System.out.println(error);
        throw e;
    }
    return null;
}

From source file:uk.co.jassoft.network.Network.java

public InputStream read(String httpUrl, String method, boolean cache) throws IOException {

    HttpURLConnection conn = null;
    try {//from   www .j  av  a 2  s  . c o m

        URL base, next;
        String location;

        while (true) {
            // inputing the keywords to google search engine
            URL url = new URL(httpUrl);

            //                if(cache) {
            //                    //Proxy instance, proxy ip = 10.0.0.1 with port 8080
            //                    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("cache", 3128));
            //                    // makking connection to the internet
            //                    conn = (HttpURLConnection) url.openConnection(proxy);
            //                }
            //                else {
            conn = (HttpURLConnection) url.openConnection();
            //                }

            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
            conn.setRequestMethod(method);
            conn.setRequestProperty("User-Agent",
                    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729)");
            conn.setRequestProperty("Accept-Encoding", "gzip");

            switch (conn.getResponseCode()) {
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
                location = conn.getHeaderField("Location");
                base = new URL(httpUrl);
                next = new URL(base, location); // Deal with relative URLs
                httpUrl = next.toExternalForm();
                continue;
            }

            break;
        }

        if (!conn.getContentType().startsWith("text/") || conn.getContentType().equals("text/xml")) {
            throw new IOException(String.format("Content of story is not Text. Returned content type is [%s]",
                    conn.getContentType()));
        }

        if ("gzip".equals(conn.getContentEncoding())) {
            return new GZIPInputStream(conn.getInputStream());
        }

        // getting the input stream of page html into bufferedreader
        return conn.getInputStream();
    } catch (Exception exception) {
        throw new IOException(exception);
    } finally {
        if (conn != null && conn.getErrorStream() != null) {
            conn.getErrorStream().close();
        }
    }
}

From source file:com.micro.http.MicroHttpClient.java

/**
  * ?,???String,?????/*  w w  w. j av a 2s.  c  o m*/
  * @param url
  * @param params
  * @return
  */
public void doRequest(final String url, final MicroRequestParams params,
        final MicroStringHttpResponseListener responseListener) {
    responseListener.setHandler(new ResponderHandler(responseListener));
    mExecutorService.execute(new Runnable() {
        public void run() {
            HttpURLConnection urlConn = null;
            try {
                responseListener.sendStartMessage();

                if (!A.isNetworkAvailable(mContext)) {
                    Thread.sleep(200);
                    responseListener.sendFailureMessage(MicroHttpStatus.CONNECT_FAILURE_CODE,
                            MicroAppConfig.CONNECT_EXCEPTION,
                            new MicroAppException(MicroAppConfig.CONNECT_EXCEPTION));
                    return;
                }

                String resultString = null;
                URL requestUrl = new URL(url);
                urlConn = (HttpURLConnection) requestUrl.openConnection();
                urlConn.setRequestMethod("POST");
                urlConn.setConnectTimeout(mTimeout);
                urlConn.setReadTimeout(mTimeout);
                urlConn.setDoOutput(true);

                if (params != null) {
                    urlConn.setRequestProperty("connection", "keep-alive");
                    urlConn.setRequestProperty("Content-Type",
                            "multipart/form-data; boundary=" + params.boundaryString());
                    MultipartEntity reqEntity = params.getMultiPart();
                    reqEntity.writeTo(urlConn.getOutputStream());
                } else {
                    urlConn.connect();
                }

                if (urlConn.getResponseCode() == HttpStatus.SC_OK) {
                    resultString = readString(urlConn.getInputStream());
                } else {
                    resultString = readString(urlConn.getErrorStream());
                }
                resultString = URLEncoder.encode(resultString, encode);
                urlConn.getInputStream().close();
                responseListener.sendSuccessMessage(MicroHttpStatus.SUCCESS_CODE, resultString);
            } catch (Exception e) {
                e.printStackTrace();
                L.I("[HTTP POST]:" + url + ",error" + e.getMessage());
                //???
                responseListener.sendFailureMessage(MicroHttpStatus.UNTREATED_CODE, e.getMessage(),
                        new MicroAppException(e));
            } finally {
                if (urlConn != null)
                    urlConn.disconnect();

                responseListener.sendFinishMessage();
            }
        }
    });
}

From source file:connection.HttpReq.java

@Override
protected String doInBackground(HttpReqPkg... params) {

    URL url;//from  w w  w  .  j av a  2s .  co  m
    BufferedReader reader = null;

    String username = params[0].getUsername();
    String password = params[0].getPassword();
    String authStringEnc = null;

    if (username != null && password != null) {
        String authString = username + ":" + password;

        byte[] authEncBytes;
        authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
        authStringEnc = new String(authEncBytes);
    }

    String uri = params[0].getUri();

    if (params[0].getMethod().equals("GET")) {
        uri += "?" + params[0].getEncodedParams();
    }

    try {
        StringBuilder sb;
        // create the HttpURLConnection
        url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        if (authStringEnc != null) {
            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }

        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")
                || params[0].getMethod().equals("DELETE")) {
            // enable writing output to this url
            connection.setDoOutput(true);
        }

        if (params[0].getMethod().equals("POST")) {
            connection.setRequestMethod("POST");
        } else if (params[0].getMethod().equals("GET")) {
            connection.setRequestMethod("GET");
        } else if (params[0].getMethod().equals("PUT")) {
            connection.setRequestMethod("PUT");
        } else if (params[0].getMethod().equals("DELETE")) {
            connection.setRequestMethod("DELETE");
        }

        // give it x seconds to respond
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setRequestProperty("Content-Type", contentType);

        for (int i = 0; i < headerMap.size(); i++) {
            connection.setRequestProperty(headerMap.keyAt(i), headerMap.valueAt(i));
        }

        connection.setRequestProperty("Content-Length", "" + params[0].getEncodedParams().getBytes().length);

        connection.connect();
        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            String httpParams = params[0].getEncodedParams();

            if (contentType.equals(OptimusHTTP.CONTENT_TYPE_JSON)) {
                httpParams = httpParams.replace("=", " ");
            }

            writer.write(httpParams);
            writer.flush();
            writer.close();
        }

        // read the output from the server
        InputStream in;
        resCode = connection.getResponseCode();
        resMsg = connection.getResponseMessage();
        if (resCode != HttpURLConnection.HTTP_OK) {
            in = connection.getErrorStream();
        } else {
            in = connection.getInputStream();
        }
        reader = new BufferedReader(new InputStreamReader(in));
        sb = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        sb.append(resCode).append(" : ").append(resMsg);
        return sb.toString();
    } catch (Exception e) {
        listener.onFailure(Integer.toString(resCode) + " : " + resMsg);
        e.printStackTrace();
    } finally {
        // close the reader; this can throw an exception too, so
        // wrap it in another try/catch block.
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    return null;
}

From source file:de.wikilab.android.friendica01.TwAjax.java

private void runFileUpload() throws IOException {

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "d1934afa-f2e4-449b-99be-8be6ebfec594";
    Log.i("Andfrnd/TwAjax", "URL=" + getURL());
    URL url = new URL(getURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);//from   ww  w.j a v a 2 s.c  om
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    //generate auth header if user/pass are provided to this class
    if (this.myHttpAuthUser != null) {
        connection.setRequestProperty("Authorization", "Basic " + Base64
                .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP));
    }
    //Log.i("Andfrnd","-->"+connection.getRequestProperty("Authorization")+"<--");

    connection.setRequestProperty("Host", url.getHost());
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    for (NameValuePair nvp : myPostData) {
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + nvp.getName() + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd + nvp.getValue() + lineEnd);
    }
    for (PostFile pf : myPostFiles) {
        pf.writeToStream(outputStream, boundary);
    }
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    myHttpStatus = connection.getResponseCode();

    outputStream.flush();
    outputStream.close();

    if (myHttpStatus < 400) {
        myResult = convertStreamToString(connection.getInputStream());
    } else {
        myResult = convertStreamToString(connection.getErrorStream());
    }

    success = true;
}

From source file:com.appcelerator.titanium.desktop.ui.wizard.Packager.java

private void publish(IProject project, File zipFile) throws UnsupportedEncodingException, MalformedURLException,
        IOException, ProtocolException, FileNotFoundException, ParseException, CoreException {
    // FIXME What if user isn't signed in? We can enforce that they must be in enablement of action, but maybe the
    // sign-in timed out or something.
    ITitaniumUser user = TitaniumCorePlugin.getDefault().getUserManager().getSignedInUser();
    Map<String, String> data = new HashMap<String, String>();
    data.put("sid", user.getSessionID()); //$NON-NLS-1$
    data.put("token", user.getToken()); //$NON-NLS-1$
    data.put("uid", user.getUID()); //$NON-NLS-1$
    data.put("uidt", user.getUIDT()); //$NON-NLS-1$

    // Post zip to url
    URL postURL = makeURL(PUBLISH_URL, data);

    IdeLog.logInfo(DesktopPlugin.getDefault(), MessageFormat.format("API Request: {0}", postURL), //$NON-NLS-1$
            com.appcelerator.titanium.core.IDebugScopes.API);

    HttpURLConnection con = (HttpURLConnection) postURL.openConnection();
    con.setUseCaches(false);/*from  w w  w.  j  ava2 s.  c o  m*/
    con.setDoOutput(true);
    con.setRequestMethod("POST"); //$NON-NLS-1$
    con.setRequestProperty("User-Agent", TitaniumConstants.USER_AGENT); //$NON-NLS-1$
    // Pipe zip contents to stream
    OutputStream out = con.getOutputStream();
    IOUtil.pipe(new BufferedInputStream(new FileInputStream(zipFile)), out);
    out.flush();
    out.close();

    // Force to finish, grab response code
    int code = con.getResponseCode();

    // Delete the destDir after POST has finished
    if (!zipFile.delete()) {
        zipFile.deleteOnExit();
    }

    // If the http code is 200 from POST, parse response as JSON. Else display error
    if (code == 200) {
        String responseText = IOUtil.read(con.getInputStream());
        IdeLog.logInfo(DesktopPlugin.getDefault(),
                MessageFormat.format("API Response: {0}:{1}", code, responseText), //$NON-NLS-1$
                com.appcelerator.titanium.core.IDebugScopes.API);

        Object result = new JSONParser().parse(responseText);

        if (result instanceof JSONObject) {
            JSONObject json = (JSONObject) result;
            boolean successful = (Boolean) json.get("success"); //$NON-NLS-1$
            if (!successful) {
                // FIXME For some reason we're failing here but Titanium Developer isn't. Bad zip file? Maybe we're
                // piping it to stream incorrectly?
                throw new CoreException(new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, code,
                        (String) json.get("message"), null)); //$NON-NLS-1$
            }
            // run pollPackagingRequest with "ticket" from JSON and project GUID if 200 and reports success
            pollPackagingRequest(project, (String) json.get("ticket")); //$NON-NLS-1$
        }
    } else {
        String responseText = IOUtil.read(con.getErrorStream());
        IdeLog.logError(DesktopPlugin.getDefault(),
                MessageFormat.format("API Response: {0}:{1}.", code, responseText), //$NON-NLS-1$
                com.appcelerator.titanium.core.IDebugScopes.API);

        throw new CoreException(new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, code,
                Messages.Packager_PackagingFailedHTTPError + code, null));
    }
}