Example usage for javax.net.ssl HttpsURLConnection getErrorStream

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

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection 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:Main.java

/**
 *
 * @param url - String//from   w  w  w .  j a  v a  2  s . co m
 * @param reqParam refer POST method
 * @param accessToken - String
 * @return ArrayList<String> 0: responseBody
 *                          1: responseCode
 */
public static ArrayList<String> getResponse(String url, String reqParam, String accessToken) {
    StringBuilder response = null;
    StringBuilder urlBuilder = null;
    BufferedReader in = null;
    HttpsURLConnection con = null;
    ArrayList<String> responseList = new ArrayList<String>();
    int responseCode = -1;
    try {
        response = new StringBuilder();

        urlBuilder = new StringBuilder();
        urlBuilder.append(url);
        urlBuilder.append("?").append(reqParam);
        urlBuilder.append("&access_token=").append(accessToken);

        URL urlObj = new URL(urlBuilder.toString());

        con = (HttpsURLConnection) urlObj.openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.setDoOutput(false);

        con.setRequestProperty("Authorization: Bearer", accessToken);
        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        responseCode = con.getResponseCode();
        String inputLine = "";
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

    } catch (Exception e) {
        in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        String inputLine = "";

        try {
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if (responseCode == -1) {

        } else {

            System.out.println(response.toString());
        }
    }

    finally {
        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    responseList.add(response.toString());
    responseList.add(String.valueOf(responseCode));
    return responseList;

}

From source file:fr.qinder.api.APIGetter.java

protected InputStream getInputStream(HttpsURLConnection request) throws IOException {
    InputStream res;/*from   ww w .j a va  2  s  . com*/

    if (request.getResponseCode() == HttpStatus.SC_OK) {
        res = request.getInputStream();
    } else {
        res = request.getErrorStream();
    }
    return res;
}

From source file:io.siddhi.doc.gen.extensions.githubclient.ContentsResponse.java

ContentsResponse(HttpsURLConnection connection) throws IOException {
    connection.setRequestProperty("Accept", "application/vnd.githubclient.v3." + mediaType());

    status = connection.getResponseCode();
    stream = (status == 200) ? connection.getInputStream() : connection.getErrorStream();

    headers = connection.getHeaderFields();

    contentsBodyReader = null;/*  w  w w.  j  ava2 s  .co m*/
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

public static String[] getAccessTokens(final String[] requests) throws Exception {
    final String TAG = "getAccesTokens";
    String code = requests[0];//from  www .j  a  v  a  2s . co m
    String clientIdAndSecret = QUIZLET_CLIENT_ID + ":" + QUIZLET_CLIENT_SECRET;
    String encodedClientIdAndSecret = Base64.encodeToString(clientIdAndSecret.getBytes(), 0);
    URL url1 = new URL("https://api.quizlet.com/oauth/token");
    HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    // Add the Basic Authorization item
    conn.addRequestProperty("Authorization", "Basic " + encodedClientIdAndSecret);

    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    String payload = String.format("grant_type=%s&code=%s&redirect_uri=%s",
            URLEncoder.encode("authorization_code", "UTF-8"), URLEncoder.encode(code, "UTF-8"),
            URLEncoder.encode(Data.RedirectURI, "UTF-8"));
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(payload);
    out.close();

    if (conn.getResponseCode() / 100 >= 3) {
        Log.e(TAG, "Http response code: " + conn.getResponseCode() + " response message: "
                + conn.getResponseMessage());
        JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
        String error = "";
        r.beginObject();
        while (r.hasNext()) {
            error += r.nextName() + r.nextString() + "\r\n";
        }
        r.endObject();
        r.close();
        Log.e(TAG, "Error response for: " + url1 + " is " + error);
        throw new IOException("Response code: " + conn.getResponseCode());
    }

    JsonReader s = new JsonReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    try {
        String accessToken = null;
        String userId = null;
        s.beginObject();
        while (s.hasNext()) {
            String name = s.nextName();
            if (name.equals("access_token")) {
                accessToken = s.nextString();
            } else if (name.equals("user_id")) {
                userId = s.nextString();
            } else {
                s.skipValue();
            }
        }
        s.endObject();
        s.close();
        return new String[] { accessToken, userId };
    } catch (Exception e) {
        // Throw out JSON exception. it is unlikely to happen
        throw new RuntimeException(e);
    } finally {
        conn.disconnect();
    }
}

From source file:org.liberty.android.fantastischmemo.downloader.cram.CramDownloadHelper.java

/**
 * Get the response String from an url with optional auth token.
 *
 * @param url the request url/*from w ww . j  ava2  s  . c  o  m*/
 * @param authToken the oauth auth token.
 * @return the response in string.
 */
private String getResponseString(URL url, String authToken) throws IOException {
    if (!Strings.isNullOrEmpty(authToken)) {
        // TODO: Add oauth here
    }

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

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new IOException(
                "Request: " + url + " HTTP response code is :" + conn.getResponseCode() + " Error: " + s);
    }
    return new String(IOUtils.toByteArray(conn.getInputStream()), "UTF-8");

}

From source file:com.illusionaryone.GoogleURLShortenerAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress, String longURL) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;// w w  w.j  av a2 s. com
    HttpsURLConnection urlConn;
    String jsonRequest = "";
    String jsonText = "";

    try {
        jsonRequest = "{ 'longUrl': '" + longURL + "'}";
        byte[] postRequest = jsonRequest.getBytes("UTF-8");

        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod("POST");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.addRequestProperty("Content-Length", String.valueOf(postRequest.length));
        urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json");
        urlConn.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");
        urlConn.connect();
        urlConn.getOutputStream().write(postRequest);

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (UnsupportedEncodingException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "UnsupportedEncodingException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err
                        .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
            }
    }

    return (jsonResult);
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call to get a new client credentials token, required for creating new account
 * //w  w w .  jav a2s  .c  o  m
 * @param url
 * @param clientCredentialsToken
 * @param httpMethod
 * @param httpBody
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws ProtocolException
 * @throws JSONException
 */
public static String getClientCredentialsResponse(Context context, String url, String clientCredentialsToken,
        String httpMethod, Bundle httpBody)
        throws MalformedURLException, IOException, ProtocolException, JSONException {
    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
        // If we have refreshed max number of times, we will not do so again
        if (refreshed == 1) {
            refreshLimitReached = true;
        }

        HttpsURLConnection connection = createSecureConnection(new URL(addParameters(context, url)));
        trustAllHosts();
        connection.setHostnameVerifier(DO_NOT_VERIFY);
        connection.setRequestMethod(httpMethod);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        String authValue = "Bearer " + clientCredentialsToken;
        connection.setRequestProperty("Authorization", authValue);
        connection.connect();

        if (!httpBody.isEmpty()) {
            OutputStream os = new BufferedOutputStream(connection.getOutputStream());
            os.write(encodePostBody(httpBody).getBytes());
            os.flush();
        }

        try {
            LoggingUtils.d(LOG_TAG, connection.toString());
            response = readFromStream(connection.getInputStream());
        } catch (FileNotFoundException e) {
            response = readFromStream(connection.getErrorStream());
        } finally {
            connection.disconnect();
        }

        // Allow for calls to return nothing
        if (response.length() == 0) {
            return "";
        }

        // Check for JSON parsing errors (will throw JSONException is can't be parsed)
        JSONObject object = new JSONObject(response);

        // If no error, return response
        if (!object.has("error")) {
            return response;
        }
        // If there is a refresh token error, refresh the token
        else if (object.getString("error").equals("invalid_token")) {
            if (refreshLimitReached) {
                // Give up
                return response;
            } else {
                // Refresh the token
                WebServiceAuthProvider.refreshAccessToken(context);
                refreshed++;
            }
        }
    } // while(!refreshLimitReached)

    return response;
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call for logging out/*from w w w.j av  a  2 s .co m*/
 * 
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws JSONException
 */
public static String getLogoutResponse(Context context)
        throws MalformedURLException, IOException, JSONException {
    // Refresh if necessary
    if (WebServiceAuthProvider.tokenExpiredHint(context)) {
        WebServiceAuthProvider.refreshAccessToken(context);
    }

    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
        // If we have refreshed max number of times, we will not do so again
        if (refreshed == 1) {
            refreshLimitReached = true;
        }

        URL url = new URL(urlForLogout(context));
        HttpsURLConnection connection = createSecureConnection(url);
        trustAllHosts();
        connection.setHostnameVerifier(DO_NOT_VERIFY);
        String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token");

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", authValue);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        try {
            LoggingUtils.d(LOG_TAG, "LogoutResponse" + connection.toString());
            response = readFromStream(connection.getInputStream());
        } catch (MalformedURLException e) {
            LoggingUtils.e(LOG_TAG,
                    "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                    null);
        } catch (IOException e) {
            response = readFromStream(connection.getErrorStream());
        } finally {
            connection.disconnect();
        }

        // Allow for calls to return nothing
        if (response.length() == 0) {
            return "";
        }

        // Check for JSON parsing errors (will throw JSONException is can't be parsed)
        JSONObject object = new JSONObject(response);

        // If no error, return response
        if (!object.has("error")) {
            return response;
        }
        // If there is a refresh token error, refresh the token
        else if (object.getString("error").equals("invalid_token")) {
            if (refreshLimitReached) {
                // Give up
                return response;
            } else {
                // Refresh the token
                WebServiceAuthProvider.refreshAccessToken(context);
                refreshed++;
            }
        }
    } // while(!refreshLimitReached)

    return response;
}

From source file:org.liberty.android.fantastischmemo.downloader.google.CellsFactory.java

public static void uploadCells(Spreadsheet spreadsheet, Worksheet worksheet, Cells cells, String authToken)
        throws IOException {
    URL url = new URL("https://spreadsheets.google.com/feeds/cells/" + spreadsheet.getId() + "/"
            + worksheet.getId() + "/private/full/batch?access_token=" + authToken);
    String urlPrefix = "https://spreadsheets.google.com/feeds/cells/" + spreadsheet.getId() + "/"
            + worksheet.getId() + "/private/full";

    for (int r = 0; r < cells.getRowCounts(); r += MAX_BATCH_SIZE) {
        int upBound = Math.min(r + MAX_BATCH_SIZE, cells.getRowCounts());

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);/*w  w  w.  j  av  a  2  s  .  c o  m*/
        conn.setDoOutput(true);
        conn.addRequestProperty("Content-Type", "application/atom+xml");
        //conn.addRequestProperty("Content-Length", "" + payload.length());
        conn.addRequestProperty("If-Match", "*");
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());

        StringBuilder head = new StringBuilder();
        head.append("<?xml version='1.0' encoding='UTF-8'?>");
        head.append(
                "<feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:batch=\"http://schemas.google.com/gdata/batch\" xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">");
        head.append("<id>" + urlPrefix + "</id>");

        out.write(head.toString());

        for (int i = r; i < upBound; i++) {
            List<String> row = cells.getRow(i);
            for (int j = 0; j < row.size(); j++) {
                out.write(getEntryToRequesetString(urlPrefix, i + 1, j + 1, row.get(j)));
            }
        }
        out.write("</feed>");

        out.close();
        if (conn.getResponseCode() / 100 >= 3) {
            String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
            throw new IOException(s);
        }
    }
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call for logging in//from  ww w  . j  a v  a  2  s . c o  m
 * 
 * @param httpBody
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws JSONException
 */
public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    trustAllHosts();
    HttpsURLConnection connection = createSecureConnection(url);
    connection.setHostnameVerifier(DO_NOT_VERIFY);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    OutputStream os = new BufferedOutputStream(connection.getOutputStream());
    os.write(encodePostBody(httpBody).getBytes());
    os.flush();
    try {
        LoggingUtils.d(LOG_TAG, connection.toString());
        response = readFromStream(connection.getInputStream());
    } catch (MalformedURLException e) {
        LoggingUtils.e(LOG_TAG,
                "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                null);
    } catch (IOException e) {
        response = readFromStream(connection.getErrorStream());
    } finally {
        connection.disconnect();
    }

    return response;
}