Example usage for java.net HttpURLConnection getErrorStream

List of usage examples for java.net HttpURLConnection getErrorStream

Introduction

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

Prototype

public InputStream getErrorStream() 

Source Link

Document

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

Usage

From source file:com.kosbrother.youtubefeeder.api.GetSuggestChannelsTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *///from  ww w.  j a v a2 s  .c o m
private void fetchNameFromProfileServer() throws IOException, JSONException {
    //        String token = fetchToken();

    String token = null;

    try {
        token = GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
    } catch (GooglePlayServicesAvailabilityException playEx) {
        // GooglePlayServices.apk is either old, disabled, or not present.
        mActivity.showErrorDialog(playEx.getConnectionStatusCode());
    } catch (UserRecoverableAuthException userRecoverableException) {
        // Unable to authenticate, but the user can fix this.
        // Forward the user to the appropriate activity.
        mActivity.startActivityForResult(userRecoverableException.getIntent(),
                RecommendChannelsActivity.REQUEST_CODE_RECOVER_FROM_AUTH_ERROR);
    } catch (GoogleAuthException fatalException) {
        onError("Unrecoverable error " + fatalException.getMessage(), fatalException);
    }

    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    //        URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    //        URL url = new URL("https://gdata.youtube.com/feeds/api/users/default/suggestion?type=channel&inline=true&access_token=" 
    //              + token  + "&key=AIzaSyC6zd4TsN6RR5mJMR_O9srbzXS9OM2R1wg" + "&v=2&max-results=10"+"fields=entry(title,media:thumbnail,yt:channelId)");
    URL url = new URL(
            "https://gdata.youtube.com/feeds/api/users/default/suggestion?type=channel&inline=true&access_token="
                    + token + "&key=AIzaSyC6zd4TsN6RR5mJMR_O9srbzXS9OM2R1wg" + "&v=2"
                    + "&fields=entry(content(entry(title)))" + "&alt=json");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    Log.i(TAG, con.getResponseMessage());
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String response = readResponse(is);
        ArrayList<Channel> channels = getChannels(response);
        //          String name = getFirstName(response);
        //          mActivity.show("Hello " + name + "!");
        is.close();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.googlecode.osde.internal.igoogle.IgCredentials.java

/**
 * Makes a HTTP POST request for authentication.
 *
 * @param emailUserName the name of the user
 * @param password the password of the user
 * @param loginTokenOfCaptcha CAPTCHA token (Optional)
 * @param loginCaptchaAnswer answer of CAPTCHA token (Optional)
 * @return http response as a String/* ww  w  . j  a  v  a 2s .  c o m*/
 * @throws IOException
 */
// TODO: Refactor requestAuthentication() utilizing HttpPost.
private static String requestAuthentication(String emailUserName, String password, String loginTokenOfCaptcha,
        String loginCaptchaAnswer) throws IOException {

    // Prepare connection.
    URL url = new URL(URL_GOOGLE_LOGIN);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
    logger.fine("url: " + url);

    // Form the POST params.
    StringBuilder params = new StringBuilder();
    params.append("Email=").append(emailUserName).append("&Passwd=").append(password)
            .append("&source=OSDE-01&service=ig&accountType=HOSTED_OR_GOOGLE");
    if (loginTokenOfCaptcha != null) {
        params.append("&logintoken=").append(loginTokenOfCaptcha);
    }
    if (loginCaptchaAnswer != null) {
        params.append("&logincaptcha=").append(loginCaptchaAnswer);
    }

    // Send POST via output stream.
    OutputStream outputStream = null;
    try {
        outputStream = urlConnection.getOutputStream();
        outputStream.write(params.toString().getBytes(IgHttpUtil.ENCODING));
        outputStream.flush();
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    // Retrieve response.
    // TODO: Should the caller of this method need to know the responseCode?
    int responseCode = urlConnection.getResponseCode();
    logger.fine("responseCode: " + responseCode);
    InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK) ? urlConnection.getInputStream()
            : urlConnection.getErrorStream();

    logger.fine("inputStream: " + inputStream);
    try {
        String response = IOUtils.toString(inputStream, IgHttpUtil.ENCODING);
        return response;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFiles() {
    URL urlO = null;/*from   ww  w  . j av a 2s  .  co  m*/
    try {
        urlO = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(fileJson.get("_id").toString());

                if (file == null) {
                    file = new File(fileJson, false);
                } else {
                    file.setName(fileJson.getString("name"));
                    file.setPath(fileJson.getString("path"));
                    file.setCreationDate(fileJson.getString("creationDate"));
                    file.setLastModification(fileJson.getString("lastModification"));
                    file.setTags(fileJson.getString("tags"));

                    if (fileJson.has("binary")) {
                        file.setBinary(fileJson.getJSONObject("binary").toString());
                    }

                    file.setIsFile(true);
                    file.setFileClass(fileJson.getString("class"));
                    file.setMimeType(fileJson.getString("mime"));
                    file.setSize(fileJson.getLong("size"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing file : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName()));

                file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory()
                        + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files"
                        + file.getPath() + "/" + file.getName()));
                file.save();

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault()
                    .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error")));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:eu.codeplumbers.cosi.services.CosiCallService.java

/**
 * Make remote request to get all calls stored in Cozy
 *///from   w w  w  .j a v a2 s . c  o  m
public String getRemoteCalls() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                Call.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE,
                            "Reading calls on Cozy " + i + "/" + jsonArray.length() + "..."));
                    JSONObject callJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Call call = Call.getByRemoteId(callJson.get("_id").toString());
                    if (call == null) {
                        call = new Call(callJson);
                    } else {
                        call.setRemoteId(callJson.getString("_id"));
                        call.setCallerId(callJson.getString("callerId"));
                        call.setCallerNumber(callJson.getString("callerNumber"));
                        call.setDuration(callJson.getLong("duration"));
                        call.setDateAndTime(callJson.getString("dateAndTime"));
                        call.setType(callJson.getInt("type"));
                    }

                    call.save();

                    allCalls.add(call);
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, errorMessage));
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:org.devnexus.aerogear.HttpRestProvider.java

private HeaderAndBody getHeaderAndBody(HttpURLConnection urlConnection) throws IOException {

    int statusCode = urlConnection.getResponseCode();
    HeaderAndBody result;//from w  ww  .  j av  a  2  s . c om
    Map<String, List<String>> headers;
    byte[] responseData;

    switch (statusCode) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        responseData = readBytes(in);

        break;

    case HttpStatus.SC_NO_CONTENT:
        responseData = new byte[0];

        break;

    default:
        InputStream err = new BufferedInputStream(urlConnection.getErrorStream());

        byte[] errData = readBytes(err);

        Map<String, String> errorHeaders = Maps.transformValues(urlConnection.getHeaderFields(),
                new Function<List<String>, String>() {
                    @Override
                    public String apply(List<String> input) {
                        return TextUtils.join(",", input);
                    }
                });

        throw new HttpException(errData, statusCode, errorHeaders);

    }

    headers = urlConnection.getHeaderFields();
    result = new HeaderAndBody(responseData, new HashMap<String, Object>(headers.size()));

    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        result.setHeader(header.getKey(), TextUtils.join(",", header.getValue()));
    }

    return result;

}

From source file:org.jboss.aerogear.android.pipe.http.HttpRestProvider.java

private HeaderAndBody getHeaderAndBody(HttpURLConnection urlConnection) throws IOException {

    int statusCode = urlConnection.getResponseCode();
    HeaderAndBody result;//from ww w  .  java2 s .  c  om
    Map<String, List<String>> headers;
    byte[] responseData;

    switch (statusCode) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        responseData = readBytes(in);

        break;

    case HttpStatus.SC_NO_CONTENT:
        responseData = new byte[0];

        break;

    default:
        InputStream err = new BufferedInputStream(urlConnection.getErrorStream());

        byte[] errData = readBytes(err);
        Map<String, List<String>> errorListHeaders = urlConnection.getHeaderFields();
        Map<String, String> errorHeaders = new HashMap<String, String>();

        for (String header : errorListHeaders.keySet()) {

            String comma = "";
            StringBuilder errorHeaderBuilder = new StringBuilder();

            for (String errorHeader : errorListHeaders.get(header)) {
                errorHeaderBuilder.append(comma).append(errorHeader);
                comma = ",";
            }

            errorHeaders.put(header, errorHeaderBuilder.toString());

        }

        throw new HttpException(errData, statusCode, errorHeaders);

    }

    headers = urlConnection.getHeaderFields();
    result = new HeaderAndBody(responseData, new HashMap<String, Object>(headers.size()));

    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        result.setHeader(header.getKey(), TextUtils.join(",", header.getValue()));
    }

    return result;

}

From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java

@Test
public void multipleValuesInAcceptHeaderWithIncorrectParam() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT,
            "application/json," + "application/json;q=0.1,application/json;q=<1");
    connection.connect();//from  ww w  .  j  a v  a  2  s  .  c o m

    assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());

    final String content = IOUtils.toString(connection.getErrorStream());
    assertTrue(content.contains("The content-type range 'application/json;q=<1' is not "
            + "supported as value of the Accept header."));
}

From source file:com.adaptris.core.http.client.net.StandardHttpProducer.java

private void handleResponse(HttpURLConnection http, AdaptrisMessage reply)
        throws IOException, InterlokException {
    int responseCode = http.getResponseCode();
    logHeaders("Response Information", http.getResponseMessage(), http.getHeaderFields().entrySet());
    log.trace("Content-Length is " + http.getContentLength());

    if (responseCode < 200 || responseCode > 299) {
        if (ignoreServerResponseCode()) {
            log.trace("Ignoring HTTP Reponse code {}", responseCode);
            responseBody().insert(new InputStreamWithEncoding(http.getErrorStream(), getContentEncoding(http)),
                    reply);//from  w ww .  j  a va  2 s  . c  o  m
        } else {
            fail(responseCode, new InputStreamWithEncoding(http.getErrorStream(), getContentEncoding(http)));
        }
    } else {
        if (getEncoder() != null) {
            AdaptrisMessage decodedReply = getEncoder().readMessage(http);
            AdaptrisMessageImp.copyPayload(decodedReply, reply);
            reply.getObjectHeaders().putAll(decodedReply.getObjectHeaders());
            reply.setMetadata(decodedReply.getMetadata());
        } else {
            responseBody().insert(new InputStreamWithEncoding(http.getInputStream(), getContentEncoding(http)),
                    reply);
        }
    }
    getResponseHeaderHandler().handle(http, reply);
    reply.addMetadata(new MetadataElement(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE,
            String.valueOf(http.getResponseCode())));
    reply.addObjectHeader(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE, Integer.valueOf(http.getResponseCode()));
}

From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java

@Test
public void multipleValuesInAcceptHeaderWithOneIncorrectValue() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT,
            "application/json," + "application/json;q=0.1,application/json;q=0.8,abc");
    connection.connect();//from w  w  w  .ja  v  a  2  s  . c  o m

    assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());

    final String content = IOUtils.toString(connection.getErrorStream());
    assertTrue(
            content.contains("The content-type range ' abc' is not supported as value of the Accept header."));
}