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:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java

public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {
    URI uri = request.getURI();/*from  ww w  .j  av  a 2  s  .c  om*/

    // Is this a CONNECT request?
    if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod())) {
        response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE????
        handleConnect(pathInContext, pathParams, request, response);
        return;
    }

    try {
        // Do we proxy this?
        URL url = isProxied(uri);
        if (url == null) {
            if (isForbidden(uri))
                sendForbid(request, response, uri);
            return;
        }

        if (log.isDebugEnabled())
            log.debug("PROXY URL=" + url);

        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.getField(HttpFields.__Connection);
        if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive)
                || connectionHdr.equalsIgnoreCase(HttpFields.__Close)))
            connectionHdr = null;

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

            if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0)
                continue;

            if (HttpFields.__ContentType.equals(hdr))
                hasContent = true;

            Enumeration vals = request.getFieldValues(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    connection.addRequestProperty(hdr, val);
                    xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr);
                }
            }
        }

        // Proxy headers
        if (!_anonymous)
            connection.setRequestProperty("Via", "1.1 (jetty)");
        if (!xForwardedFor)
            connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr());

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

        // customize Connection
        customizeConnection(pathInContext, pathParams, request, connection);

        try {
            connection.setDoInput(true);

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

            // Connect
            connection.connect();
        } catch (Exception e) {
            LogSupport.ignore(log, e);
        }

        InputStream proxy_in = null;

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

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

        if (proxy_in == null) {
            try {
                proxy_in = connection.getInputStream();
            } catch (Exception e) {
                LogSupport.ignore(log, e);
                proxy_in = http.getErrorStream();
            }
        }

        // clear response defaults.
        response.removeField(HttpFields.__Date);
        response.removeField(HttpFields.__Server);

        // set response headers
        int h = 0;
        String hdr = connection.getHeaderFieldKey(h);
        String val = connection.getHeaderField(h);
        while (hdr != null || val != null) {
            if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr)
                    && (_chained || !_ProxyAuthHeaders.containsKey(hdr)))
                response.addField(hdr, val);
            h++;
            hdr = connection.getHeaderFieldKey(h);
            val = connection.getHeaderField(h);
        }
        if (!_anonymous)
            response.setField("Via", "1.1 (jetty)");

        // Handled
        request.setHandled(true);
        if (proxy_in != null)
            IO.copy(proxy_in, response.getOutputStream());

    } catch (Exception e) {
        log.warn(e.toString());
        LogSupport.ignore(log, e);
        if (!response.isCommitted())
            response.sendError(HttpResponse.__400_Bad_Request);
    }
}

From source file:com.techventus.server.voice.Voice.java

/**
 * HTTP GET request for a given URL String.
 * //from  w w w. ja  v a  2s. c  o  m
 * @param urlString
 *            the url string
 * @return the string
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
String get(String urlString) throws IOException {
    URL url = new URL(urlString);
    //+ "?auth=" + URLEncoder.encode(authToken, enc));

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    conn.setRequestProperty("User-agent", USER_AGENT);
    conn.setInstanceFollowRedirects(false); // will follow redirects of same protocol http to http, but does not follow from http to https for example if set to true

    // Get the response
    conn.connect();
    int responseCode = conn.getResponseCode();
    if (PRINT_TO_CONSOLE)
        System.out.println(urlString + " - " + conn.getResponseMessage());
    InputStream is;
    if (responseCode == 200) {
        is = conn.getInputStream();
    } else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
            || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
            || responseCode == HttpURLConnection.HTTP_SEE_OTHER || responseCode == 307) {
        redirectCounter++;
        if (redirectCounter > MAX_REDIRECTS) {
            redirectCounter = 0;
            throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                    + ") : Too manny redirects. exiting.");
        }
        String location = conn.getHeaderField("Location");
        if (location != null && !location.equals("")) {
            System.out.println(urlString + " - " + responseCode + " - new URL: " + location);
            return get(location);
        } else {
            throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                    + ") : Received moved answer but no Location. exiting.");
        }
    } else {
        is = conn.getErrorStream();
    }
    redirectCounter = 0;

    if (is == null) {
        throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                + ") : InputStream was null : exiting.");
    }

    String result = "";
    try {
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line + "\n\r");
        }
        rd.close();
        result = sb.toString();
    } catch (Exception e) {
        throw new IOException(urlString + " - " + conn.getResponseMessage() + "(" + responseCode + ") - "
                + e.getLocalizedMessage());
    }
    return result;
}

From source file:com.gotraveling.external.androidquery.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;/* www  . j  a va2 s  .c  o  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);

}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

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

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);/*from   w ww  .  j  ava 2  s. 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";
    }

    // Check user preference to see if YouTube videos should be private by
    // default.
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
    Boolean ytPrivate = prefs.getBoolean("defaultYouTubePrivatePreference", true);

    String private_or_not = "<yt:private />";
    if (!ytPrivate) {
        private_or_not = "";
    }

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

    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;

        mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT);

        // 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.

                ((VidiomActivity) activity).finishedUploading(false);
                ((VidiomActivity) 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, sdrecord_id);
        } else {

            mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT);

            // 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.

                    ((VidiomActivity) activity).finishedUploading(false);
                    ((VidiomActivity) 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.gdevelop.gwt.syncrpc.RemoteServiceSyncProxy.java

public Object doInvoke(RequestCallbackAdapter.ResponseReader responseReader, String requestData)
        throws Throwable {
    HttpURLConnection connection = null;
    InputStream is = null;//from   w  ww. j  av  a  2s  . co m
    int statusCode;

    if (DUMP_PAYLOAD) {
        log.debug("Send request to {}", remoteServiceURL);
        log.debug("Request payload: {}", requestData);
    }

    // Send request
    CookieHandler oldCookieHandler = CookieHandler.getDefault();
    try {
        CookieHandler.setDefault(cookieManager);

        URL url = new URL(remoteServiceURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty(RpcRequestBuilder.STRONG_NAME_HEADER, serializationPolicyName);
        connection.setRequestProperty(RpcRequestBuilder.MODULE_BASE_HEADER, moduleBaseURL);
        connection.setRequestProperty("Content-Type", "text/x-gwt-rpc; charset=utf-8");
        connection.setRequestProperty("Content-Length", "" + requestData.getBytes("UTF-8").length);

        CookieStore store = cookieManager.getCookieStore();
        String cookiesStr = "";

        for (HttpCookie cookie : store.getCookies()) {
            if (!"".equals(cookiesStr))
                cookiesStr += "; ";
            cookiesStr += cookie.getName() + "=" + cookie.getValue();
        }

        connection.setRequestProperty("Cookie", cookiesStr);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(requestData);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new InvocationException("IOException while sending RPC request", e);
    } finally {
        CookieHandler.setDefault(oldCookieHandler);
    }

    // Receive and process response
    try {

        is = connection.getInputStream();
        statusCode = connection.getResponseCode();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }
        String encodedResponse = baos.toString("UTF8");
        if (DUMP_PAYLOAD) {
            log.debug("Response code: {}", statusCode);
            log.debug("Response payload: {}", encodedResponse);
        }

        // System.out.println("Response payload (len = " + encodedResponse.length() + "): " + encodedResponse);
        if (statusCode != HttpURLConnection.HTTP_OK) {
            throw new StatusCodeException(statusCode, encodedResponse);
        } else if (encodedResponse == null) {
            // This can happen if the XHR is interrupted by the server dying
            throw new InvocationException("No response payload");
        } else if (isReturnValue(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            return responseReader.read(createStreamReader(encodedResponse));
        } else if (isThrownException(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            Throwable throwable = (Throwable) createStreamReader(encodedResponse).readObject();
            throw throwable;
        } else {
            throw new InvocationException("Unknown response " + encodedResponse);
        }
    } catch (IOException e) {

        log.error("error response: {}", IOUtils.toString(connection.getErrorStream()));
        throw new InvocationException("IOException while receiving RPC response", e);

    } catch (SerializationException e) {
        throw new InvocationException("Error while deserialization response", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (connection != null) {
            // connection.disconnect();
        }
    }
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

public String doRedirect(String urlRedirect, boolean useTim) {
    // android.os.Debug.waitForDebugger();
    try {//  www  .jav a 2s .  c  o m
        // with server phpOIDC, check for '#'
        if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?"))
                || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) {
            String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&");
            String code = "";
            String state = "";
            String state_key = "state";
            for (int i = 0; i < params.length; i++) {
                String param = params[i];
                int idxEqual = param.indexOf('=');
                if (idxEqual >= 0) {
                    String key = param.substring(0, idxEqual);
                    String value = param.substring(idxEqual + 1);
                    if (key.startsWith("code"))
                        code = value;
                    if (key.startsWith("state"))
                        state = value;
                    if (key.startsWith("session_state")) {
                        state = value;
                        state_key = "session_state";
                    }
                }
            }

            // display code and state
            Logd(TAG, "doRedirect => code: " + code + " / state: " + state);

            // doRepost(code,state);
            if (code.length() > 0) {

                // get token_endpoint endpoint
                String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url);
                if (isEmpty(token_endpoint)) {
                    Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url);
                    return null;
                }

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                HttpURLConnection huc = getHUC(token_endpoint);
                huc.setInstanceFollowRedirects(false);

                if (useTim) {
                    if (mUsePrivateKeyJWT) {
                        nameValuePairs.add(new BasicNameValuePair("client_assertion_type",
                                "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));
                        String client_assertion = secureStorage.getPrivateKeyJwt(token_endpoint);
                        Logd(TAG, "client_assertion: " + client_assertion);
                        nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion));
                    } else {
                        huc.setRequestProperty("Authorization",
                                "Basic " + secureStorage.getClientSecretBasic());
                    }
                } else {
                    String authorization = (mOcp.m_client_id + ":" + mOcp.m_client_secret);
                    authorization = Base64.encodeToString(authorization.getBytes(), Base64.DEFAULT);
                    huc.setRequestProperty("Authorization", "Basic " + authorization);
                }

                huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                huc.setDoOutput(true);
                huc.setChunkedStreamingMode(0);

                OutputStream os = huc.getOutputStream();
                OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8");
                BufferedWriter writer = new BufferedWriter(out);

                nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
                nameValuePairs.add(new BasicNameValuePair("code", code));
                nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri));
                if (state != null && state.length() > 0)
                    nameValuePairs.add(new BasicNameValuePair(state_key, state));

                // write URL encoded string from list of key value pairs
                writer.write(getQuery(nameValuePairs));
                writer.flush();
                writer.close();
                out.close();
                os.close();

                Logd(TAG, "doRedirect => before connect");
                huc.connect();
                int responseCode = huc.getResponseCode();
                System.out.println("2 - code " + responseCode);
                Log.d(TAG, "doRedirect => responseCode " + responseCode);
                InputStream in = null;
                try {
                    in = new BufferedInputStream(huc.getInputStream());
                } catch (IOException ioe) {
                    sysout("io exception: " + huc.getErrorStream());
                }
                if (in != null) {
                    String result = convertStreamToString(in);
                    // now you have the string representation of the HTML request
                    in.close();

                    Logd(TAG, "doRedirect: " + result);

                    // save as static for now
                    return result;

                } else {
                    Logd(TAG, "doRedirect null");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.workfront.api.StreamClient.java

private Object request(String path, Map<String, Object> params, Set<String> fields, String method,
        int retryCount, File file) throws StreamClientException {
    HttpURLConnection conn = null;
    int responseCode = -1;

    try {/*from   w w w. j  ava  2 s . com*/
        String authenticationParam = "";
        if (apiKey != null) {
            authenticationParam += "apiKey=" + apiKey;
        } else if (sessionID != null) {
            authenticationParam += "sessionID=" + sessionID;
        }
        String methodParam = "method=" + method;
        String query = authenticationParam + "&" + methodParam;

        if (params != null) {
            for (String key : params.keySet()) {
                if (params.get(key) instanceof String[]) {
                    String[] paramVal = (String[]) params.get(key);
                    for (int i = 0; i < paramVal.length; i++) {
                        String val = paramVal[i];
                        query += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(val, "UTF-8");
                    }
                } else {
                    query += "&" + URLEncoder.encode(key, "UTF-8") + "="
                            + URLEncoder.encode(String.valueOf(params.get(key)), "UTF-8");
                }
            }
        }

        if (fields != null) {
            query += "&fields=";
            for (String field : fields) {
                query += URLEncoder.encode(field, "UTF-8") + ",";
            }
            query = query.substring(0, query.lastIndexOf(","));
        }

        conn = createConnection(hostname + path, method);

        String boundary = Long.toHexString(System.currentTimeMillis());

        if (file != null) {
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            conn.setRequestProperty("User-Agent", "Workfront Java StreamClient");
        }

        // Send request
        OutputStream outputStream = conn.getOutputStream();
        Writer out = new OutputStreamWriter(outputStream);
        if (file != null) {
            addFileToRequest(boundary, out, outputStream, file);
        } else {
            out.write(query);
        }

        out.flush();
        out.close();

        // Get response code
        responseCode = conn.getResponseCode();

        // Read response
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = in.readLine()) != null) {
            response.append(line);
        }

        in.close();

        // Decode JSON
        JSONObject result = new JSONObject(response.toString());

        // Verify result
        if (result.has("error")) {
            throw new StreamClientException(result.getJSONObject("error").getString("message"));
        } else if (!result.has("data")) {
            throw new StreamClientException("Invalid response from server");
        }

        // Manage the session
        if (path.equals(PATH_LOGIN)) {
            sessionID = result.getJSONObject("data").getString("sessionID");
        } else if (path.equals(PATH_LOGOUT)) {
            sessionID = null;
        }

        return result.get("data");
    } catch (ConnectException connectException) {
        throw new StreamClientException("Unable to connect to " + hostname + path);
    } catch (IOException e) {
        //getErrorStream() can return null if no error data was sent back
        if (conn.getErrorStream() != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            try {
                copyStream(conn.getErrorStream(), out);
            } catch (IOException e1) {
                // Removed printStackTrace call
            }

            throw new StreamClientException(new String(out.toByteArray()));
        } else {
            //I believe this use case happens when the we are sending to many requests at one time...
            if (retryCount < 3) {
                return request(path, params, fields, method, ++retryCount);
            } else {
                throw new StreamClientException(
                        "An error happened but no error data was sent... 3 time... Response Code = "
                                + responseCode);
            }
        }
    } catch (Exception e) {
        throw new StreamClientException(e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.canappi.connector.yp.yhere.SearchView.java

public ArrayList<Element> searchByZip(HashMap<String, String> requestParameters) {

    ArrayList<Element> data = new ArrayList<Element>();

    System.setProperty("http.keepAlive", "false");
    System.setProperty("javax.net.debug", "all");
    // _FakeX509TrustManager.allowAllSSL();

    //Protocol::: HTTP GET
    StringBuffer query = new StringBuffer();

    HttpURLConnection connection = null;

    try {/*from   w  ww  . j  a  v  a 2  s. c  o  m*/
        URL url;

        if (requestParameters != null) {
            String key;

            query.append(
                    "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a");
            query.append("&");
            key = "term";
            String termValue = requestParameters.get(key);
            String termDefaultValue = retrieveFromUserDefaultsFor(key);
            if (termValue.length() > 0) {
                query.append("" + key + "=" + requestParameters.get(key));
            } else {
                //try to find the value in the user defaults
                if (termDefaultValue != null) {
                    query.append("" + key + "=" + retrieveFromUserDefaultsFor(key));
                }
            }
            key = "searchloc";
            String searchlocValue = requestParameters.get(key);
            String searchlocDefaultValue = retrieveFromUserDefaultsFor(key);
            if (searchlocValue.length() > 0) {
                query.append("&" + key + "=" + requestParameters.get(key));
            } else {
                //try to find the value in the user defaults
                if (searchlocDefaultValue != null) {
                    query.append("&" + key + "=" + retrieveFromUserDefaultsFor(key));
                }
            }

            url = new URL(query.toString());

        } else {

            url = new URL(
                    "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a");
        }

        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setUseCaches(false);

        connection.setRequestMethod("GET");

        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.connect();

        int rc = connection.getResponseCode();
        Log.i("Response code", String.valueOf(rc));
        InputStream is;
        if (rc <= 400) {
            is = connection.getInputStream();
        } else {
            /* error from server */
            is = connection.getErrorStream();
        }

        //XML ResultSet

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource isrc = new InputSource();
            isrc.setByteStream(is);

            Document doc = db.parse(isrc);
            NodeList nodes = doc.getElementsByTagName("searchListings");

            if (nodes.getLength() > 0) {
                Element list = (Element) nodes.item(0);
                NodeList l = list.getChildNodes();
                for (int i = 0; i < l.getLength(); i++) {
                    Node n = l.item(i);
                    if (n.getNodeType() == Node.ELEMENT_NODE) {
                        Element row = (Element) l.item(i);
                        data.add(row);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    finally {
        connection.disconnect();
    }

    return data;

}

From source file:core.AbstractTest.java

private int httpRequest(String sUrl, String sMethod, JsonNode payload, Map<String, String> mParameters) {
    Logger.info("\n\nREQUEST:\n" + sMethod + " " + sUrl + "\nHEADERS: " + mHeaders + "\nParameters: "
            + mParameters + "\nPayload: " + payload + "\n");
    HttpURLConnection conn = null;
    BufferedReader br = null;/*from  ww  w.ja v a2s  .c om*/
    int nRet = 0;
    boolean fIsMultipart = false;

    try {
        setStatusCode(-1);
        setResponse(null);
        conn = getHttpConnection(sUrl, sMethod);
        if (mHeaders.size() > 0) {
            Set<String> keys = mHeaders.keySet();
            for (String sKey : keys) {
                conn.addRequestProperty(sKey, mHeaders.get(sKey));
                if (sKey.equals(HTTP.CONTENT_TYPE)) {
                    if (mHeaders.get(sKey).startsWith(MediaType.MULTIPART_FORM_DATA)) {
                        fIsMultipart = true;
                    }
                }
            }
        }

        if (payload != null || mParameters != null) {
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());

            try {
                if (payload != null) {
                    //conn.setRequestProperty("Content-Length", "" + node.toString().length());
                    out.writeBytes(payload.toString());
                }

                if (mParameters != null) {
                    Set<String> sKeys = mParameters.keySet();

                    if (fIsMultipart) {
                        out.writeBytes("--" + BOUNDARY + "\r\n");
                    }

                    for (String sKey : sKeys) {
                        if (fIsMultipart) {
                            out.writeBytes("Content-Disposition: form-data; name=\"" + sKey + "\"\r\n\r\n");
                            out.writeBytes(mParameters.get(sKey));
                            out.writeBytes("\r\n");
                            out.writeBytes("--" + BOUNDARY + "--\r\n");
                        } else {
                            out.writeBytes(URLEncoder.encode(sKey, "UTF-8"));
                            out.writeBytes("=");
                            out.writeBytes(URLEncoder.encode(mParameters.get(sKey), "UTF-8"));
                            out.writeBytes("&");
                        }
                    }

                    if (fIsMultipart) {
                        if (nvpFile != null) {
                            File f = Play.application().getFile(nvpFile.getName());
                            if (f == null) {
                                assertFail("Cannot find file <" + nvpFile.getName() + ">");
                            }
                            FileBody fb = new FileBody(f);
                            out.writeBytes("Content-Disposition: form-data; name=\"" + PARAM_FILE
                                    + "\";filename=\"" + fb.getFilename() + "\"\r\n");
                            out.writeBytes("Content-Type: " + nvpFile.getValue() + "\r\n\r\n");
                            out.write(getResource(nvpFile.getName()));
                        }
                        out.writeBytes("\r\n--" + BOUNDARY + "--\r\n");
                    }
                }
            } catch (Exception ex) {
                assertFail("Send request: " + ex.getMessage());
            } finally {
                try {
                    out.flush();
                } catch (Exception ex) {
                }
                try {
                    out.close();
                } catch (Exception ex) {
                }
            }
        }

        nRet = conn.getResponseCode();
        setStatusCode(nRet);
        if (nRet / 100 != 2) {
            if (conn.getErrorStream() != null) {
                br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            }
        } else {
            if (conn.getInputStream() != null) {
                br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            }
        }

        if (br != null) {
            String temp = null;
            StringBuilder sb = new StringBuilder(1024);
            while ((temp = br.readLine()) != null) {
                sb.append(temp).append("\n");
            }
            setResponse(sb.toString().trim());
        }
        Logger.info("\nRESPONSE\nHTTP code: " + nRet + "\nContent: " + sResponse + "\n");
    } catch (Exception ex) {
        assertFail("httpRequest: " + ex.getMessage());
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (Exception ex) {
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return nRet;
}