Example usage for javax.net.ssl HttpsURLConnection addRequestProperty

List of usage examples for javax.net.ssl HttpsURLConnection addRequestProperty

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection addRequestProperty.

Prototype

public void addRequestProperty(String key, String value) 

Source Link

Document

Adds a general request property specified by a key-value pair.

Usage

From source file:com.dao.ShopThread.java

private HttpsURLConnection getHttpSConn(String httpsurl) throws Exception {
    // SSLContext??
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    // Acts like a browser
    URL obj = new URL(httpsurl);
    HttpsURLConnection conn;
    conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory(ssf);/*from  w  ww  . j a va 2s  .  com*/
    conn.setRequestMethod("GET");
    if (null != this.cookies) {
        conn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies));
    }
    conn.setRequestProperty("Host", "security.5173.com");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    conn.setRequestProperty("Connection", "keep-alive");
    conn.setRequestProperty("Pragma", "no-cache");
    conn.setRequestProperty("Cache-Control", "no-cache");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    return conn;
}

From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java

private InputStream processGetRequest(URL url, String keyStore, String keyStorePassword) {
    SSLSocketFactory sslFactory = getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con = null;
    try {//from  w  w w  . ja  v  a  2 s .  co m
        con = (HttpsURLConnection) url.openConnection();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }
    con.setSSLSocketFactory(sslFactory);
    try {
        con.setRequestMethod(REQUEST_METHOD_GET);
    } catch (ProtocolException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }

    con.addRequestProperty(X_MS_VERSION_HEADER, X_MS_VERSION);

    InputStream responseStream = null;
    try {
        responseStream = (InputStream) con.getContent();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }

    return responseStream;
}

From source file:com.pearson.pdn.learningstudio.core.AbstractService.java

/**
 * Performs HTTP operations using the selected authentication method
 * //from   ww  w. j  av a2  s  .  c o m
 * @param extraHeaders   Extra headers to include in the request
 * @param method   The HTTP Method to user
 * @param relativeUrl   The URL after .com (/me)
 * @param body   The body of the message
 * @return Output in the preferred data format
 * @throws IOException
 */
protected Response doMethod(Map<String, String> extraHeaders, HttpMethod method, String relativeUrl,
        String body) throws IOException {

    if (body == null) {
        body = "";
    }

    // append .xml extension when XML data format enabled.
    if (dataFormat == DataFormat.XML) {
        logger.debug("Using XML extension on route");

        String queryString = "";
        int queryStringIndex = relativeUrl.indexOf('?');
        if (queryStringIndex != -1) {
            queryString = relativeUrl.substring(queryStringIndex);
            relativeUrl = relativeUrl.substring(0, queryStringIndex);
        }

        String compareUrl = relativeUrl.toLowerCase();

        if (!compareUrl.endsWith(".xml")) {
            relativeUrl += ".xml";
        }

        if (queryStringIndex != -1) {
            relativeUrl += queryString;
        }
    }

    final String fullUrl = API_DOMAIN + relativeUrl;

    if (logger.isDebugEnabled()) {
        logger.debug("REQUEST - Method: " + method.name() + ", URL: " + fullUrl + ", Body: " + body);
    }

    URL url = new URL(fullUrl);
    Map<String, String> oauthHeaders = getOAuthHeaders(method, url, body);

    if (oauthHeaders == null) {
        throw new RuntimeException("Authentication method not selected. SEE useOAuth# methods");
    }

    if (extraHeaders != null) {
        for (String key : extraHeaders.keySet()) {
            if (!oauthHeaders.containsKey(key)) {
                oauthHeaders.put(key, extraHeaders.get(key));
            } else {
                throw new RuntimeException("Extra headers can not include OAuth headers");
            }
        }
    }

    HttpsURLConnection request = (HttpsURLConnection) url.openConnection();
    try {
        request.setRequestMethod(method.toString());

        Set<String> oauthHeaderKeys = oauthHeaders.keySet();
        for (String oauthHeaderKey : oauthHeaderKeys) {
            request.addRequestProperty(oauthHeaderKey, oauthHeaders.get(oauthHeaderKey));
        }

        request.addRequestProperty("User-Agent", getServiceIdentifier());

        if ((method == HttpMethod.POST || method == HttpMethod.PUT) && body.length() > 0) {
            if (dataFormat == DataFormat.XML) {
                request.setRequestProperty("Content-Type", "application/xml");
            } else {
                request.setRequestProperty("Content-Type", "application/json");
            }

            request.setRequestProperty("Content-Length", String.valueOf(body.getBytes("UTF-8").length));
            request.setDoOutput(true);

            DataOutputStream out = new DataOutputStream(request.getOutputStream());
            try {
                out.writeBytes(body);
                out.flush();
            } finally {
                out.close();
            }
        }

        Response response = new Response();
        response.setMethod(method.toString());
        response.setUrl(url.toString());
        response.setStatusCode(request.getResponseCode());
        response.setStatusMessage(request.getResponseMessage());
        response.setHeaders(request.getHeaderFields());

        InputStream inputStream = null;
        if (response.getStatusCode() < ResponseStatus.BAD_REQUEST.code()) {
            inputStream = request.getInputStream();
        } else {
            inputStream = request.getErrorStream();
        }

        boolean isBinary = false;
        if (inputStream != null) {
            StringBuilder responseBody = new StringBuilder();

            String contentType = request.getContentType();
            if (contentType != null) {
                if (!contentType.startsWith("text/") && !contentType.startsWith("application/xml")
                        && !contentType.startsWith("application/json")) { // assume binary
                    isBinary = true;
                    inputStream = new Base64InputStream(inputStream, true); // base64 encode
                }
            }

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            try {
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    responseBody.append(line);
                }
            } finally {
                bufferedReader.close();
            }

            response.setContentType(contentType);

            if (isBinary) {
                String content = responseBody.toString();
                if (content.length() == 0) {
                    response.setBinaryContent(new byte[0]);
                } else {
                    response.setBinaryContent(Base64.decodeBase64(responseBody.toString()));
                }
            } else {
                response.setContent(responseBody.toString());
            }
        }

        if (logger.isDebugEnabled()) {
            if (isBinary) {
                logger.debug("RESPONSE - binary response omitted");
            } else {
                logger.debug("RESPONSE - " + response.toString());
            }
        }

        return response;
    } finally {
        request.disconnect();
    }

}

From source file:com.gmt2001.TwitchAPIv5.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;/*from  ww  w  .j  a  va 2  s  .  com*/
    String content = "";

    try {
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();
        c.addRequestProperty("Accept", header_accept);
        c.addRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded");

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        } else {
            if (!this.oauth.isEmpty()) {
                c.addRequestProperty("Authorization", "OAuth " + oauth);
            }
        }

        c.setRequestMethod(type.name());
        c.setConnectTimeout(timeout);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        c.connect();

        if (!post.isEmpty()) {
            try (OutputStream o = c.getOutputStream()) {
                IOUtils.write(post, o);
            }
        }

        if (c.getResponseCode() == 200) {
            i = c.getInputStream();
        } else {
            i = c.getErrorStream();
        }

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            // default to UTF-8, it'll probably be the best bet if there's
            // no charset specified.
            String charset = "utf-8";
            String ct = c.getContentType();
            if (ct != null) {
                String[] cts = ct.split(" *; *");
                for (int idx = 1; idx < cts.length; ++idx) {
                    String[] val = cts[idx].split("=", 2);
                    if (val[0] == "charset" && val.length > 1) {
                        charset = val[1];
                    }
                }
            }

            if ("gzip".equals(c.getContentEncoding())) {
                i = new GZIPInputStream(i);
            }

            content = IOUtils.toString(i, charset);
        }

        j = new JSONObject(content);
        fillJSONObject(j, true, type.name(), post, url, c.getResponseCode(), "", "", content);
    } catch (Exception ex) {
        Throwable rootCause = ex;
        while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
            rootCause = rootCause.getCause();
        }

        fillJSONObject(j, false, type.name(), post, url, 0, ex.getClass().getSimpleName(), ex.getMessage(),
                content);
        com.gmt2001.Console.debug
                .println("Failed to get data [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage());
    } finally {
        if (i != null) {
            try {
                i.close();
            } catch (IOException ex) {
                fillJSONObject(j, false, type.name(), post, url, 0, "IOException", ex.getMessage(), content);
                com.gmt2001.Console.err.println("IOException: " + ex.getMessage());
            }
        }
    }

    return j;
}

From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java

private String addAuthentication(HttpsURLConnection con) {
    String auth = _app + ":" + _secret;
    byte[] auth64 = Base64.encodeBase64(auth.getBytes());
    String data = "Basic " + new String(auth64);
    if (con != null)
        con.addRequestProperty("Authorization", data);
    return data;/*  w  w w.  j  ava  2  s. c o  m*/
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Tries to download the contents of the provided url using not commercially validated CA certificate from chosen provider.
 *
 * @param url_string as a string/*from   ww  w  .  j a  v a 2  s  . c  o  m*/
 * @return an empty string if it fails, the url content if not.
 */
private String downloadWithProviderCA(String url_string) {
    String json_file_content = "";

    try {
        URL url = new URL(url_string);
        // Tell the URLConnection to use a SocketFactory from our SSLContext
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory());
        if (!LeapSRPSession.getToken().isEmpty())
            urlConnection.addRequestProperty(LeapSRPSession.AUTHORIZATION_HEADER,
                    "Token token=" + LeapSRPSession.getToken());
        json_file_content = new Scanner(urlConnection.getInputStream()).useDelimiter("\\A").next();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        json_file_content = formatErrorMessage(R.string.server_unreachable_message);
    } catch (IOException e) {
        // The downloaded certificate doesn't validate our https connection.
        json_file_content = formatErrorMessage(R.string.certificate_error);
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchElementException e) {
        e.printStackTrace();
        json_file_content = formatErrorMessage(R.string.server_unreachable_message);
    }
    return json_file_content;
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private String downloadWithCommercialCA(String url_string, String ca_cert_fingerprint) {
    String result = "";

    int seconds_of_timeout = 2;
    String[] pins = new String[] { ca_cert_fingerprint };
    try {//from w w  w  .  ja va 2  s  .  co m
        URL url = new URL(url_string);
        HttpsURLConnection connection = PinningHelper.getPinnedHttpsURLConnection(Dashboard.getContext(), pins,
                url);
        connection.setConnectTimeout(seconds_of_timeout * 1000);
        if (!LeapSRPSession.getToken().isEmpty())
            connection.addRequestProperty(LeapSRPSession.AUTHORIZATION_HEADER,
                    "Token token = " + LeapSRPSession.getToken());
        result = new Scanner(connection.getInputStream()).useDelimiter("\\A").next();
    } catch (IOException e) {
        if (e instanceof SSLHandshakeException)
            result = formatErrorMessage(R.string.error_security_pinnedcertificate);
        else
            result = formatErrorMessage(R.string.error_io_exception_user_message);
    }

    return result;
}

From source file:iracing.webapi.IracingWebApi.java

/**
 * /*from  www  .ja v a 2s .c o m*/
 * @return a login response code
 * @throws IOException
 * @throws LoginException 
 * @see #LOGIN_RESPONSE_SUCCESS
 * @see #LOGIN_RESPONSE_CONNECTION_ERROR
 * @see #LOGIN_RESPONSE_DOWN_FOR_MAINTAINENCE
 * @see #LOGIN_RESPONSE_FAILED_CREDENTIALS
 */
public LoginResponse login() throws IOException, LoginException {
    try {
        installCerts();
    } catch (Exception e1) {
        e1.printStackTrace();
        throw new LoginException("error whilst attempting to install SSL certificates");
    }

    System.setProperty("javax.net.ssl.trustStore", "jssecacerts");
    System.setProperty("javax.net.ssl.trustStorePassword", CERT_STORE_PASSWORD);

    if (loginRequiredHandler == null)
        return LoginResponse.ConfigError;
    IracingLoginCredentials creds = new IracingLoginCredentials();
    if (!loginRequiredHandler.onLoginCredentialsRequired(creds))
        return LoginResponse.CredentialsError;
    String encodedUsername = URLEncoder.encode(creds.getEmailAddress(), "UTF-8");
    String encodedPW = URLEncoder.encode(creds.getPassword(), "UTF-8");

    String urltext = LOGIN_URL + "?username=" + encodedUsername + "&password=" + encodedPW; // + "&utcoffset=-60&todaysdate=";

    URL url = new URL(urltext);

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    conn.addRequestProperty("Content-Length", "0");

    conn.setInstanceFollowRedirects(false);
    HttpsURLConnection.setFollowRedirects(false);

    try {
        conn.connect();
    } catch (Exception e) {
        e.printStackTrace();
        throw new LoginException(e.getMessage());
    }

    if (isMaintenancePage(conn))
        return LoginResponse.DownForMaintenance;

    String headerName;
    for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
        if (headerName.equalsIgnoreCase(SET_COOKIE)) {
            addToCookieMap(conn.getHeaderField(i));
        } else {
            if (!headerName.equals("Location")) {
                continue;
            }
            String location2 = conn.getHeaderField(i);

            if (location2.indexOf("failedlogin") != -1) {
                throw new LoginException("You have been directed to the failed login page");
            }
        }
    }
    createCookieFromMap();

    conn.disconnect();

    return LoginResponse.Success;
}

From source file:com.echopf.ECHOQuery.java

/**
 * Sends a HTTP request with optional request contents/parameters.
 * @param path a request url path//from w w  w.j  ava2  s .  c  o  m
 * @param httpMethod a request method (GET/POST/PUT/DELETE)
 * @param data request contents/parameters
 * @param multipart use multipart/form-data to encode the contents
 * @throws ECHOException
 */
public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart)
        throws ECHOException {
    final String secureDomain = ECHO.secureDomain;
    if (secureDomain == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    String baseUrl = new StringBuilder("https://").append(secureDomain).toString();
    String url = new StringBuilder(baseUrl).append("/").append(path).toString();

    HttpsURLConnection httpClient = null;

    try {
        URL urlObj = new URL(url);

        StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/");

        // Append the QueryString contained in path
        boolean isContainQuery = urlObj.getQuery() != null;
        if (isContainQuery)
            apiUrl.append("?").append(urlObj.getQuery());

        // Append the QueryString from data
        if (httpMethod.equals("GET") && data != null) {
            boolean firstItem = true;
            Iterator<?> iter = data.keys();
            while (iter.hasNext()) {
                if (firstItem && !isContainQuery) {
                    firstItem = false;
                    apiUrl.append("?");
                } else {
                    apiUrl.append("&");
                }
                String key = (String) iter.next();
                String value = data.optString(key);
                apiUrl.append(key);
                apiUrl.append("=");
                apiUrl.append(value);
            }
        }

        URL urlConn = new URL(apiUrl.toString());
        httpClient = (HttpsURLConnection) urlConn.openConnection();
    } catch (IOException e) {
        throw new ECHOException(e);
    }

    final String appId = ECHO.appId;
    final String appKey = ECHO.appKey;
    final String accessToken = ECHO.accessToken;

    if (appId == null || appKey == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    InputStream responseInputStream = null;

    try {
        httpClient.setRequestMethod(httpMethod);
        httpClient.addRequestProperty("X-ECHO-APP-ID", appId);
        httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey);

        // Set access token
        if (accessToken != null && !accessToken.isEmpty())
            httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken);

        // Build content
        if (!httpMethod.equals("GET") && data != null) {

            httpClient.setDoOutput(true);
            httpClient.setChunkedStreamingMode(0); // use default chunk size

            if (multipart == false) { // application/json

                httpClient.addRequestProperty("CONTENT-TYPE", "application/json");
                BufferedWriter wrBuffer = new BufferedWriter(
                        new OutputStreamWriter(httpClient.getOutputStream()));
                wrBuffer.write(data.toString());
                wrBuffer.close();

            } else { // multipart/form-data

                final String boundary = "*****" + UUID.randomUUID().toString() + "*****";
                final String twoHyphens = "--";
                final String lineEnd = "\r\n";
                final int maxBufferSize = 1024 * 1024 * 3;

                httpClient.setRequestMethod("POST");
                httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary);

                final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream());

                try {

                    JSONObject postData = new JSONObject();
                    postData.putOpt("method", httpMethod);
                    postData.putOpt("data", data);

                    new Object() {

                        public void post(JSONObject data, List<String> currentKeys)
                                throws JSONException, IOException {

                            Iterator<?> keys = data.keys();
                            while (keys.hasNext()) {
                                String key = (String) keys.next();
                                List<String> newKeys = new ArrayList<String>(currentKeys);
                                newKeys.add(key);

                                Object val = data.get(key);

                                // convert JSONArray into JSONObject
                                if (val instanceof JSONArray) {
                                    JSONArray array = (JSONArray) val;
                                    JSONObject val2 = new JSONObject();

                                    for (Integer i = 0; i < array.length(); i++) {
                                        val2.putOpt(i.toString(), array.get(i));
                                    }

                                    val = val2;
                                }

                                // build form-data name
                                String name = "";
                                for (int i = 0; i < newKeys.size(); i++) {
                                    String key2 = newKeys.get(i);
                                    name += (i == 0) ? key2 : "[" + key2 + "]";
                                }

                                if (val instanceof ECHOFile) {

                                    ECHOFile file = (ECHOFile) val;
                                    if (file.getLocalBytes() == null)
                                        continue;

                                    InputStream fileInputStream = new ByteArrayInputStream(
                                            file.getLocalBytes());

                                    if (fileInputStream != null) {

                                        String mimeType = URLConnection
                                                .guessContentTypeFromName(file.getFileName());

                                        // write header
                                        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name
                                                + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd);
                                        outputStream.writeBytes("Content-Type: " + mimeType + lineEnd);
                                        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
                                        outputStream.writeBytes(lineEnd);

                                        // write content
                                        int bytesAvailable, bufferSize, bytesRead;
                                        do {
                                            bytesAvailable = fileInputStream.available();
                                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                            byte[] buffer = new byte[bufferSize];
                                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                                            if (bytesRead <= 0)
                                                break;
                                            outputStream.write(buffer, 0, bufferSize);
                                        } while (true);

                                        fileInputStream.close();
                                        outputStream.writeBytes(lineEnd);
                                    }

                                } else if (val instanceof JSONObject) {

                                    this.post((JSONObject) val, newKeys);

                                } else {

                                    String data2 = null;
                                    try { // in case of boolean
                                        boolean bool = data.getBoolean(key);
                                        data2 = bool ? "true" : "";
                                    } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false".
                                        data2 = val.toString().trim();
                                    }

                                    // write header
                                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                    outputStream.writeBytes(
                                            "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd);
                                    outputStream
                                            .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
                                    outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd);
                                    outputStream.writeBytes(lineEnd);

                                    // write content
                                    byte[] bytes = data2.getBytes();
                                    for (int i = 0; i < bytes.length; i++) {
                                        outputStream.writeByte(bytes[i]);
                                    }

                                    outputStream.writeBytes(lineEnd);
                                }

                            }
                        }
                    }.post(postData, new ArrayList<String>());

                } catch (JSONException e) {

                    throw new ECHOException(e);

                } finally {

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

                }
            }

        } else {

            httpClient.addRequestProperty("CONTENT-TYPE", "application/json");

        }

        if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) {
            responseInputStream = httpClient.getInputStream();
        }

    } catch (IOException e) {

        // get http response code
        int errorCode = -1;

        try {
            errorCode = httpClient.getResponseCode();
        } catch (IOException e1) {
            throw new ECHOException(e1);
        }

        // get error contents
        JSONObject responseObj;
        try {
            String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream());
            responseObj = new JSONObject(jsonStr);
        } catch (JSONException e1) {
            if (errorCode == 404) {
                throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found.");
            }

            throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format.");
        }

        //
        if (responseObj != null) {
            int code = responseObj.optInt("error_code");
            String message = responseObj.optString("error_message");

            if (code != 0 || !message.equals("")) {
                JSONObject details = responseObj.optJSONObject("error_details");
                if (details == null) {
                    throw new ECHOException(code, message);
                } else {
                    throw new ECHOException(code, message, details);
                }
            }
        }

        throw new ECHOException(e);

    }

    return responseInputStream;
}