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.fidku.geoluks.social.google.AbstractGetNameTask.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   www .  j  a  va2 s  . co  m
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    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);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String result = readResponse(is);
        final JSONObject res = new JSONObject(result);

        System.out.println(result);
        String name = getFirstName(result);
        // mActivity.show(mEmail+" - "+ res.getString("name")+" - "+ res.getString("id")+" - "+ "Google+");

        is.close();
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    mActivity.sessionIniciada(mEmail, res.getString("name"), res.getString("id"), "Google+");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        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.example.pabrto.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;/*from   www . jav a  2 s  . c  om*/
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }
            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");

                // ...

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }
            if (response == null) {
                int a = conn.getResponseCode();
                InputStream a1 = conn.getErrorStream();
                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": "
                + e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return response;
}

From source file:it.govpay.web.rs.Check.java

@GET
@Path("/pdd")
public Response verificaPDD(@QueryParam(value = "matchString") String matchString) {
    Logger log = LogManager.getLogger();
    try {/*from w ww .ja  v a 2  s. c om*/
        try {
            URL url = GovpayConfig.getInstance().getUrlPddVerifica();
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            String checkResult = null;
            conn.connect();

            int responseCode = conn.getResponseCode();

            String bodyResponse = null;

            if (responseCode > 299) {
                checkResult = "Ottenuto response code [" + responseCode + "] durante la connessione a [" + url
                        + "]";
            }

            if (matchString != null) {
                checkResult = null;

                if (responseCode < 300) {
                    if (conn.getInputStream() != null) {
                        bodyResponse = new String(
                                conn.getInputStream() != null ? IOUtils.toByteArray(conn.getInputStream())
                                        : new byte[] {});
                    }
                } else {
                    if (conn.getErrorStream() != null) {
                        bodyResponse = new String(
                                conn.getErrorStream() != null ? IOUtils.toByteArray(conn.getErrorStream())
                                        : new byte[] {});
                    }
                }

                if (bodyResponse == null || !bodyResponse.contains(matchString))
                    checkResult = "Ottenuta risposta che non contiene la matchString [" + matchString
                            + "] durante la connessione a [" + url + "]";
            }

            if (checkResult != null)
                throw new Exception(checkResult);

        } catch (Exception e) {
            log.error("Errore di connessione alla PDD", e);
            throw new Exception("Errore di connessione alla PDD: " + e.getMessage());
        }

        return Response.ok().build();
    } catch (Exception e) {
        return Response.status(500).entity(e.getMessage()).build();
    }
}

From source file:com.skplanet.syruppay.client.SyrupPayClientTest.java

@Test
public void testGet_Sso_WITH_BASIC_AUTHENTICATION() throws IOException {
    URL url = new URL(
            "https://devqapay.syrup.co.kr/v1/api-basic/merchants/sktmall_s002/sso-credentials/create");

    String encoding = org.apache.commons.codec.binary.Base64
            .encodeBase64String("sktmall_s002:W9n7yLQrpt2Sm1zpqFpxr9k95BWNRXxs".getBytes());

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);//from  w w w.j  av  a  2  s .c om
    connection.setRequestProperty("Authorization", "Basic " + encoding);
    connection.setRequestProperty("Accept", "application/jose");
    connection.setRequestProperty("Content-type", "application/jose");

    JoseHeader h = new JoseHeader(Jwa.A128KW, Jwa.A128CBC_HS256, "sktmall_s001");
    String request = new Jose().configuration(JoseBuilders
            .JsonEncryptionCompactSerializationBuilder().header(h).payload("{\n" + "    \"ssoIdentifier\": {\n"
                    + "        \"mctUserId\" : \"15644623-3\"\n" + "    }\n" + "}")
            .key("G3aIW7hYmlTjag3FDc63OGLNWwvagVUU")).serialization();

    OutputStream out = connection.getOutputStream();
    out.write(request.getBytes());
    out.close();

    try {
        int status = connection.getResponseCode();
        InputStream content;
        if (status == 200) {
            content = connection.getInputStream();
        } else {
            content = connection.getErrorStream();
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line;
        StringBuilder buf = new StringBuilder();
        while ((line = in.readLine()) != null) {
            buf.append(line);
        }

        String response = new Jose().configuration(JoseBuilders.compactDeserializationBuilder()
                .serializedSource(buf.toString()).key("G3aIW7hYmlTjag3FDc63OGLNWwvagVUU")).deserialization();

        System.out.println(response);

        in.close();
    } catch (FileNotFoundException fe) {
        // ? ?
        System.out.println("User Not Found");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.graylog2.alarmcallbacks.pagerduty.PagerDutyClient.java

public void trigger(final Stream stream, final AlertCondition.CheckResult checkResult)
        throws AlarmCallbackException {
    final URL url;
    try {//from w w  w .j ava 2s .c  o m
        url = new URL(API_URL);
    } catch (MalformedURLException e) {
        throw new AlarmCallbackException("Malformed URL for PagerDuty API.", e);
    }

    final HttpURLConnection conn;
    try {
        if (httpProxyUri != null) {
            final InetSocketAddress proxyAddress = new InetSocketAddress(httpProxyUri.getHost(),
                    httpProxyUri.getPort());
            final Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
            conn = (HttpURLConnection) url.openConnection(proxy);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        conn.setRequestMethod("POST");
    } catch (IOException e) {
        throw new AlarmCallbackException("Error while opening connection to PagerDuty API.", e);
    }

    conn.setDoOutput(true);

    try (final OutputStream requestStream = conn.getOutputStream()) {
        final PagerDutyEvent event = buildPagerDutyEvent(stream, checkResult);
        requestStream.write(objectMapper.writeValueAsBytes(event));
        requestStream.flush();

        final InputStream responseStream;
        if (conn.getResponseCode() == 200) {
            responseStream = conn.getInputStream();
        } else {
            responseStream = conn.getErrorStream();
        }

        final PagerDutyResponse response = objectMapper.readValue(responseStream, PagerDutyResponse.class);
        if ("success".equals(response.status)) {
            LOG.debug("Successfully sent event to PagerDuty with incident key {}", response.incidentKey);
        } else {
            LOG.warn("Error while creating event at PagerDuty: {} ({})", response.message, response.errors);
            throw new AlarmCallbackException("Error while creating event at PagerDuty: " + response.message);
        }
    } catch (IOException e) {
        throw new AlarmCallbackException("Could not POST event trigger to PagerDuty API.", e);
    }
}

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

/**
 * Make remote request to get all calls stored in Cozy
 *///ww  w .ja  v a2 s  . c  om
public void getRemoteContacts() {
    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 ContactSyncEvent(SYNC_MESSAGE, "Your Cozy has no contacts stored."));
                Contact.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    Log.d("Contact", i + "");
                    EventBus.getDefault().post(new ContactSyncEvent(SYNC_MESSAGE,
                            "Reading contacts on Cozy " + (i + 1) + "/" + jsonArray.length() + "..."));
                    try {

                        JSONObject contactJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        Contact contact = Contact.getByRemoteId(contactJson.get("_id").toString());
                        if (contact == null) {
                            contact = Contact.getByName(contactJson.getString("n"));
                            if (contact == null) {
                                contact = new Contact(contactJson);
                            } else {
                                if (contactJson.has("n"))
                                    contact.setN(contactJson.getString("n"));
                                else
                                    contact.setN("");

                                if (contactJson.has("fn"))
                                    contact.setFn(contactJson.getString("fn"));
                                else
                                    contact.setFn("");

                                if (contactJson.has("revision")) {
                                    contact.setRevision(contactJson.getString("revision"));
                                } else {
                                    contact.setRevision(DateUtils.formatDate(new Date().getTime()));
                                }

                                if (contactJson.has("tags")
                                        && !contactJson.getString("tags").equalsIgnoreCase("")) {
                                    contact.setTags(contactJson.getJSONArray("tags").toString());
                                } else {
                                    contact.setTags(new JSONArray().toString());
                                }
                                contact.setPhotoBase64("");
                                contact.setAnniversary("");

                                if (contactJson.has("deviceId")) {
                                    contact.setDeviceId(contactJson.getString("deviceId"));
                                }

                                if (contactJson.has("systemId")) {
                                    contact.setSystemId(contactJson.getString("systemId"));
                                }

                                contact.setRemoteId(contactJson.getString("_id"));

                                if (contactJson.has("_attachments")) {
                                    JSONObject attachment = contactJson.getJSONObject("_attachments");

                                    contact.setAttachments(attachment.toString());

                                    if (attachment.has("picture")) {
                                        JSONObject picture = attachment.getJSONObject("picture");
                                        String attachmentName = new String(
                                                Base64.decode(picture.getString("digest").replace("md5-", ""),
                                                        Base64.DEFAULT));
                                        Log.d("Contact", attachmentName);
                                    }
                                }

                                contact.save();

                                if (contactJson.has("datapoints")) {
                                    JSONArray datapoints = contactJson.getJSONArray("datapoints");

                                    for (int j = 0; j < datapoints.length(); j++) {
                                        JSONObject datapoint = datapoints.getJSONObject(j);
                                        String value = datapoint.getString("value");
                                        ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact,
                                                value);

                                        if (contactDataPoint == null && !value.isEmpty()) {
                                            contactDataPoint = new ContactDataPoint();
                                            contactDataPoint.setPref(false);
                                            contactDataPoint.setType(datapoint.getString("type"));
                                            contactDataPoint.setValue(value);
                                            contactDataPoint.setName(datapoint.getString("name"));
                                            contactDataPoint.setContact(contact);
                                            contactDataPoint.save();
                                        }
                                    }
                                }
                            }
                        } else {
                            if (contactJson.has("n"))
                                contact.setN(contactJson.getString("n"));
                            else
                                contact.setN("");

                            if (contactJson.has("fn"))
                                contact.setFn(contactJson.getString("fn"));
                            else
                                contact.setFn("");

                            if (contactJson.has("revision")) {
                                contact.setRevision(contactJson.getString("revision"));
                            } else {
                                contact.setRevision(DateUtils.formatDate(new Date().getTime()));
                            }

                            if (contactJson.has("tags")
                                    && !contactJson.getString("tags").equalsIgnoreCase("")) {
                                contact.setTags(contactJson.getJSONArray("tags").toString());
                            } else {
                                contact.setTags(new JSONArray().toString());
                            }
                            contact.setPhotoBase64("");
                            contact.setAnniversary("");

                            if (contactJson.has("deviceId")) {
                                contact.setDeviceId(contactJson.getString("deviceId"));
                            }

                            if (contactJson.has("systemId")) {
                                contact.setSystemId(contactJson.getString("systemId"));
                            }

                            contact.setRemoteId(contactJson.getString("_id"));

                            if (contactJson.has("_attachments")) {
                                JSONObject attachment = contactJson.getJSONObject("_attachments");

                                contact.setAttachments(attachment.toString());

                                if (attachment.has("picture")) {
                                    JSONObject picture = attachment.getJSONObject("picture");
                                    String attachmentName = new String(Base64.decode(
                                            picture.getString("digest").replace("md5-", ""), Base64.DEFAULT));
                                    Log.d("Contact", attachmentName);
                                }
                            }

                            contact.save();

                            if (contactJson.has("datapoints")) {
                                JSONArray datapoints = contactJson.getJSONArray("datapoints");

                                for (int j = 0; j < datapoints.length(); j++) {
                                    JSONObject datapoint = datapoints.getJSONObject(j);
                                    String value = datapoint.getString("value");
                                    ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact,
                                            value);

                                    if (contactDataPoint == null && !value.isEmpty()) {
                                        contactDataPoint = new ContactDataPoint();
                                        contactDataPoint.setPref(false);
                                        contactDataPoint.setType(datapoint.getString("type"));
                                        contactDataPoint.setValue(value);
                                        contactDataPoint.setName(datapoint.getString("name"));
                                        contactDataPoint.setContact(contact);
                                        contactDataPoint.save();
                                    }
                                }
                            }
                        }

                        contact.save();

                        allContacts.add(contact);
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

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

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

From source file:com.server.xmpp.Sender.java

/**
 * Sends a message without retrying in case of service unavailability. See
 * {@link #send(Message, String, int)} for more info.
 *
 * @return result of the post, or {@literal null} if the GCM service was
 *         unavailable or any network exception caused the request to fail.
 *
 * @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
 * @throws IllegalArgumentException if registrationId is {@literal null}.
 *//*from   w ww .  java 2 s .c o m*/
public Result sendNoRetry(Message message, String registrationId) throws IOException {
    StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId);
    Boolean delayWhileIdle = message.isDelayWhileIdle();
    if (delayWhileIdle != null) {
        addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0");
    }
    Boolean dryRun = message.isDryRun();
    if (dryRun != null) {
        addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0");
    }
    String collapseKey = message.getCollapseKey();
    if (collapseKey != null) {
        addParameter(body, PARAM_COLLAPSE_KEY, collapseKey);
    }
    String restrictedPackageName = message.getRestrictedPackageName();
    if (restrictedPackageName != null) {
        addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName);
    }
    Integer timeToLive = message.getTimeToLive();
    if (timeToLive != null) {
        addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive));
    }
    for (Entry<String, String> entry : message.getData().entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (key == null || value == null) {
            logger.warning("Ignoring payload entry thas has null: " + entry);
        } else {
            key = PARAM_PAYLOAD_PREFIX + key;
            addParameter(body, key, URLEncoder.encode(value, UTF8));
        }
    }
    String requestBody = body.toString();
    logger.finest("Request body: " + requestBody);
    HttpURLConnection conn;
    int status;
    try {
        conn = post(GCM_SEND_ENDPOINT, requestBody);
        status = conn.getResponseCode();
    } catch (IOException e) {
        logger.log(Level.FINE, "IOException posting to GCM", e);
        return null;
    }
    if (status / 100 == 5) {
        logger.info("GCM service is unavailable (status " + status + ")");
        return null;
    }
    String responseBody;
    if (status != 200) {
        try {
            responseBody = getAndClose(conn.getErrorStream());
            logger.finest("Plain post error response: " + responseBody);
        } catch (IOException e) {
            // ignore the exception since it will thrown an InvalidRequestException
            // anyways
            responseBody = "N/A";
            logger.log(Level.FINE, "Exception reading response: ", e);
        }
        throw new InvalidRequestException(status, responseBody);
    } else {
        try {
            responseBody = getAndClose(conn.getInputStream());
        } catch (IOException e) {
            logger.log(Level.WARNING, "Exception reading response: ", e);
            // return null so it can retry
            return null;
        }
    }
    String[] lines = responseBody.split("\n");
    if (lines.length == 0 || lines[0].equals("")) {
        throw new IOException("Received empty response from GCM service.");
    }
    String firstLine = lines[0];
    String[] responseParts = split(firstLine);
    String token = responseParts[0];
    String value = responseParts[1];
    if (token.equals(TOKEN_MESSAGE_ID)) {
        Builder builder = new Result.Builder().messageId(value);
        // check for canonical registration id
        if (lines.length > 1) {
            String secondLine = lines[1];
            responseParts = split(secondLine);
            token = responseParts[0];
            value = responseParts[1];
            if (token.equals(TOKEN_CANONICAL_REG_ID)) {
                builder.canonicalRegistrationId(value);
            } else {
                logger.info("Invalid response from GCM: " + responseBody);
            }
        }
        Result result = builder.build();
        if (logger.isLoggable(Level.FINE)) {
            logger.info("Message created succesfully (" + result + ")");
        }
        return result;
    } else if (token.equals(TOKEN_ERROR)) {
        return new Result.Builder().errorCode(value).build();
    } else {
        throw new IOException("Invalid response from GCM: " + responseBody);
    }
}

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

/**
 * Synchronous call to the OCC web services
 * // ww  w . j  av  a 2  s . c  o  m
 * @param url
 *           The url
 * @param isAuthorizedRequest
 *           Whether this request requires the authorization token sending
 * @param httpMethod
 *           method type (GET, PUT, POST, DELETE)
 * @param httpBody
 *           Data to be sent in the body (Can be empty)
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws ProtocolException
 */
public static String getResponse(Context context, String url, Boolean isAuthorizedRequest, String httpMethod,
        Bundle httpBody) throws MalformedURLException, IOException, ProtocolException, JSONException {
    // Refresh if necessary
    if (isAuthorizedRequest && 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;
        }

        // Make the connection and get the response
        OutputStream os;
        HttpURLConnection connection;

        if (httpMethod.equals("GET") && httpBody != null && !httpBody.isEmpty()) {
            url = url + "?" + encodePostBody(httpBody);
        }
        URL requestURL = new URL(addParameters(context, url));

        if (StringUtils.equalsIgnoreCase(requestURL.getProtocol(), "https")) {
            trustAllHosts();
            HttpsURLConnection https = createSecureConnection(requestURL);
            https.setHostnameVerifier(DO_NOT_VERIFY);
            if (isAuthorizedRequest) {
                String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token");
                https.setRequestProperty("Authorization", authValue);
            }
            connection = https;
        } else {
            connection = createConnection(requestURL);
        }
        connection.setRequestMethod(httpMethod);

        if (!httpMethod.equals("GET") && !httpMethod.equals("DELETE")) {
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();

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

        response = "";
        try {
            LoggingUtils.d(LOG_TAG, connection.toString());
            response = readFromStream(connection.getInputStream());
        } catch (FileNotFoundException e) {
            LoggingUtils.e(LOG_TAG,
                    "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                    context);
            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)

    // There is an error other than a refresh error, so return the response
    return response;
}

From source file:com.mycompany.grupo6ti.GenericResource.java

@POST
@Produces("application/json")
@Path("/cancelarFactura/{id}/{motivo}")
public String anularFactura(@PathParam("id") String id, @PathParam("motivo") String motivo) {
    try {// www.j  a v a 2  s .c  om
        URL url = new URL("http://localhost:85/cancel/");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        InputStream is;
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setUseCaches(true);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        String idJson = "{\n" + "  \"id\": \"" + id + "\",\n" + "  \"motivo\": \"" + motivo + "\"\n" + "}";
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(idJson);
        out.flush();
        out.close();

        if (conn.getResponseCode() >= 400) {
            is = conn.getErrorStream();
        } else {
            is = conn.getInputStream();
        }
        String result2 = "";
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = rd.readLine()) != null) {
            result2 += line;
        }
        rd.close();
        return result2;

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

    return ("[\"Test\", \"Funcionando Bien\"]");

}

From source file:org.whispersystems.textsecure.push.PushServiceSocket.java

private HttpURLConnection makeBaseRequest(String urlFragment, String method, String body)
        throws NonSuccessfulResponseCodeException, PushNetworkException {
    HttpURLConnection connection = getConnection(urlFragment, method, body);
    int responseCode;
    String responseMessage;/*w  w  w.j  a  v a2  s  . c  o m*/
    String response;

    try {
        responseCode = connection.getResponseCode();
        responseMessage = connection.getResponseMessage();
    } catch (IOException ioe) {
        throw new PushNetworkException(ioe);
    }

    switch (responseCode) {
    case 413:
        connection.disconnect();
        throw new RateLimitException("Rate limit exceeded: " + responseCode);
    case 401:
    case 403:
        connection.disconnect();
        throw new AuthorizationFailedException("Authorization failed!");
    case 404:
        connection.disconnect();
        throw new NotFoundException("Not found");
    case 409:
        try {
            response = Util.readFully(connection.getErrorStream());
        } catch (IOException e) {
            throw new PushNetworkException(e);
        }
        throw new MismatchedDevicesException(new Gson().fromJson(response, MismatchedDevices.class));
    case 410:
        try {
            response = Util.readFully(connection.getErrorStream());
        } catch (IOException e) {
            throw new PushNetworkException(e);
        }
        throw new StaleDevicesException(new Gson().fromJson(response, StaleDevices.class));
    case 417:
        throw new ExpectationFailedException();
    }

    if (responseCode != 200 && responseCode != 204) {
        throw new NonSuccessfulResponseCodeException("Bad response: " + responseCode + " " + responseMessage);
    }

    return connection;
}