Example usage for javax.net.ssl HttpsURLConnection getResponseMessage

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

Introduction

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

Prototype

public String getResponseMessage() throws IOException 

Source Link

Document

Gets the HTTP response message, if any, returned along with the response code from a server.

Usage

From source file:xyz.karpador.godfishbot.commands.GofCommand.java

@Override
public CommandResult getReply(String params, Message message, String myName) {
    if (params == null)
        return new CommandResult(getUsage() + "\n" + getDescription());
    CommandResult result = new CommandResult();
    try {/*from  w w w.ja  v  a  2  s. c  o m*/
        String urlString = "https://gifbase.com/tag/" + params + "?format=json";
        URL url = new URL(urlString);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setConnectTimeout(4000);
        if (con.getResponseCode() == HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder httpResult = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
                httpResult.append(line);
            JSONObject resultJson = new JSONObject(httpResult.toString());
            int pageCount = resultJson.optInt("page_count", 1);
            if (pageCount > 1) {
                int page = Main.Random.nextInt(pageCount - 1) + 1;
                if (page != resultJson.getInt("page_current")) {
                    urlString += "&p=" + page;
                    url = new URL(urlString);
                    con = (HttpsURLConnection) url.openConnection();
                    con.setConnectTimeout(4000);
                    if (con.getResponseCode() == HTTP_OK) {
                        br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                        httpResult.setLength(0);
                        while ((line = br.readLine()) != null)
                            httpResult.append(line);
                        resultJson = new JSONObject(httpResult.toString());
                    }
                }
            }
            JSONArray gifs = resultJson.optJSONArray("gifs");
            if (gifs != null) {
                JSONObject gif = gifs.getJSONObject(Main.Random.nextInt(gifs.length()));
                result.imageUrl = gif.getString("url");
            } else
                return null;
        } else {
            return new CommandResult("gifbase.com responded with error code: " + con.getResponseCode() + ": "
                    + con.getResponseMessage());
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
        return null;
    }
    if (result.imageUrl == null)
        return null;
    result.isGIF = true;
    return result;
}

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

/**
 * Performs HTTP operations using the selected authentication method
 * //from   w  w w .j  a  v  a2s .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:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java

public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {

    RestResponse restResponse = new RestResponse();
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");
    // add request header
    if (headers != null) {
        for (Entry<String, String> header : headers.entrySet()) {
            String key = header.getKey();
            String value = header.getValue();
            con.setRequestProperty(key, value);
        }/*from   w  w  w . jav  a 2  s. c  o m*/

    }

    int responseCode = con.getResponseCode();
    logger.debug("Send GET http request, url: {}", url);
    logger.debug("Response Code: {}", responseCode);

    StringBuffer response = new StringBuffer();
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    } catch (Exception e) {
        logger.debug("response body is null");
    }

    String result;

    try {

        result = IOUtils.toString(con.getErrorStream());
        response.append(result);

    } catch (Exception e2) {
        // result = null;
    }
    logger.debug("Response body: {}", response);

    // print result

    restResponse.setErrorCode(responseCode);

    if (response != null) {
        restResponse.setResponse(response.toString());
    }

    restResponse.setErrorCode(responseCode);
    // restResponse.setResponse(result);
    Map<String, List<String>> headerFields = con.getHeaderFields();
    restResponse.setHeaderFields(headerFields);
    String responseMessage = con.getResponseMessage();
    restResponse.setResponseMessage(responseMessage);

    con.disconnect();

    return restResponse;
}

From source file:xyz.karpador.godfishbot.commands.MLPCommand.java

@Override
public CommandResult getReply(String params, Message message, String myName) {
    if (params == null)
        return new CommandResult(getUsage() + "\n" + getDescription());
    CommandResult result = new CommandResult();
    try {//ww  w . j  a  va2  s. co m
        String urlString = "https://derpibooru.org/search.json?q="
                + URLEncoder.encode(params, "UTF-8").replace("%20", "+");
        URL url = new URL(urlString);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        if (con.getResponseCode() == HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder httpResult = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
                httpResult.append(line);
            JSONObject resultJson = new JSONObject(httpResult.toString());
            int totalHits = resultJson.getInt("total");
            if (totalHits < 1) {
                result.replyToId = message.getMessageId();
                result.text = "No results found.";
                return result;
            }
            int pageNumber = 1;
            if (totalHits > 20) // Generate a valid page number.
                pageNumber = Main.Random.nextInt((int) Math.ceil(totalHits / 20)) + 1;
            if (pageNumber > 1) {
                urlString += "&page=" + pageNumber;
                url = new URL(urlString);
                con = (HttpsURLConnection) url.openConnection();
                if (con.getResponseCode() == HTTP_OK) {
                    br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    httpResult.setLength(0);
                    while ((line = br.readLine()) != null)
                        httpResult.append(line);
                    resultJson = new JSONObject(httpResult.toString());
                }
            }
            JSONArray hits = resultJson.getJSONArray("search");
            int imageIndex = Main.Random.nextInt(hits.length());
            JSONObject img = hits.getJSONObject(imageIndex);
            result.imageUrl = "https:" + img.getString("image");
            if (result.imageUrl.toLowerCase().endsWith(".gif"))
                result.isGIF = true;
            if (knownImages.containsKey(result.imageUrl))
                result.mediaId = knownImages.get(result.imageUrl);
            result.text = "From derpibooru.org";
            //+ "(Source: " + img.getString("source_url") + ")";
            if (!img.isNull("source_url"))
                result.text += " (Source: " + img.getString("source_url") + ")";
        } else {
            result.text = "derpibooru.org returned error code " + con.getResponseCode() + ": "
                    + con.getResponseMessage();
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
        return null;
    }
    return result;
}

From source file:org.openymsg.network.Session.java

private String[] yahooAuth16Stage2(final String token, final String seed)
        throws LoginRefusedException, IOException, NoSuchAlgorithmException {
    String loginLink = "https://" + this.yahooLoginHost + "/config/pwtoken_login?src=ymsgr&ts=&token=" + token;

    URL u = new URL(loginLink);
    URLConnection uc = u.openConnection();
    uc.setConnectTimeout(LOGIN_HTTP_TIMEOUT);

    if (uc instanceof HttpsURLConnection) {
        trustEveryone();/*from   w  w  w  . j  a  v  a  2 s  . c  om*/
        HttpsURLConnection httpUc = (HttpsURLConnection) uc;

        if (!this.yahooLoginHost.equalsIgnoreCase(LOGIN_YAHOO_COM))
            httpUc.setHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(final String hostname, final SSLSession session) {
                    return true;
                }
            });

        int responseCode = httpUc.getResponseCode();
        this.setSessionStatus(SessionState.STAGE2);
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream in = uc.getInputStream();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int read = -1;
            byte[] buff = new byte[256];
            while ((read = in.read(buff)) != -1)
                out.write(buff, 0, read);

            int responseNo = -1;
            String crumb = null;
            String cookieY = null;
            String cookieT = null;

            StringTokenizer toks = new StringTokenizer(out.toString(), "\r\n");
            if (toks.countTokens() <= 0)
                // errrorrrr
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 2:" + httpUc.getResponseMessage());

            try {
                responseNo = Integer.valueOf(toks.nextToken());
            } catch (NumberFormatException e) {
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 2:" + httpUc.getResponseMessage());
            }

            if (responseNo != 0 || !toks.hasMoreTokens())
                throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD);

            while (toks.hasMoreTokens()) {
                String t = toks.nextToken();
                if (t.startsWith("crumb="))
                    crumb = t.replaceAll("crumb=", "");
                else if (t.startsWith("Y="))
                    cookieY = t.replaceAll("Y=", "");
                else if (t.startsWith("T="))
                    cookieT = t.replaceAll("T=", "");
            }

            if (crumb == null || cookieT == null || cookieY == null)
                throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD);

            // Iterator<String> iter =
            // ((HttpURLConnection) uc).getHeaderFields().get("Set-Cookie").iterator();
            // while (iter.hasNext())
            // {
            // String string = iter.next();
            // System.out.println("\t" + string);
            // }
            this.cookieY = cookieY;
            this.cookieT = cookieT;
            return yahooAuth16Stage3(crumb + seed, cookieY, cookieT);
        }
    }

    throw new LoginRefusedException("Login Failed, unable to retrieve stage 2 url");
}

From source file:org.openymsg.network.Session.java

private String[] yahooAuth16Stage1(final String seed)
        throws LoginRefusedException, IOException, NoSuchAlgorithmException {
    String authLink = "https://" + this.yahooLoginHost + "/config/pwtoken_get?src=ymsgr&ts=&login="
            + this.loginID.getId() + "&passwd=" + URLEncoder.encode(this.password, "UTF-8") + "&chal="
            + URLEncoder.encode(seed, "UTF-8");

    URL u = new URL(authLink);
    URLConnection uc = u.openConnection();
    uc.setConnectTimeout(LOGIN_HTTP_TIMEOUT);

    if (uc instanceof HttpsURLConnection) {
        HttpsURLConnection httpUc = (HttpsURLConnection) uc;
        // used to simulate failures
        //             if  (triesBeforeFailure++ % 3 == 0) {
        //                 throw new SocketException("Test failure");
        //             }
        if (!this.yahooLoginHost.equalsIgnoreCase(LOGIN_YAHOO_COM))
            httpUc.setHostnameVerifier(new HostnameVerifier() {

                @Override/* ww  w  . j ava  2 s  . c  o m*/
                public boolean verify(final String hostname, final SSLSession session) {
                    Principal principal = null;
                    try {
                        principal = session.getPeerPrincipal();
                    } catch (SSLPeerUnverifiedException e) {
                    }
                    String localName = "no set";
                    if (principal != null)
                        localName = principal.getName();
                    log.debug("Hostname verify: " + hostname + "localName: " + localName);
                    return true;
                }
            });

        int responseCode = httpUc.getResponseCode();
        this.setSessionStatus(SessionState.STAGE1);
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream in = uc.getInputStream();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int read = -1;
            byte[] buff = new byte[256];
            while ((read = in.read(buff)) != -1)
                out.write(buff, 0, read);
            in.close();

            StringTokenizer toks = new StringTokenizer(out.toString(), "\r\n");
            if (toks.countTokens() <= 0)
                // errrorrrr
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 1:" + httpUc.getResponseMessage());

            int responseNo = -1;
            try {
                responseNo = Integer.valueOf(toks.nextToken());
            } catch (NumberFormatException e) {
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 1:" + httpUc.getResponseMessage());
            }

            if (responseNo != 0 || !toks.hasMoreTokens())
                switch (responseNo) {
                case 1235:
                    throw new LoginRefusedException("Login Failed, Invalid username",
                            AuthenticationState.BADUSERNAME);
                case 1212:
                    throw new LoginRefusedException("Login Failed, Wrong password", AuthenticationState.BAD);
                case 1213:
                    throw new LoginRefusedException("Login locked: Too many failed login attempts",
                            AuthenticationState.LOCKED);
                case 1236:
                    throw new LoginRefusedException("Login locked", AuthenticationState.LOCKED);
                case 100:
                    throw new LoginRefusedException("Username or password missing", AuthenticationState.BAD);
                default:
                    throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD);
                }

            String ymsgr = toks.nextToken();

            if (ymsgr.indexOf("ymsgr=") == -1 && toks.hasMoreTokens())
                ymsgr = toks.nextToken();

            ymsgr = ymsgr.replaceAll("ymsgr=", "");

            return yahooAuth16Stage2(ymsgr, seed);
        } else {
            log.error("Failed opening login url: " + authLink + " return code: " + responseCode);
            throw new LoginRefusedException(
                    "Login Failed, Login url: " + authLink + " return code: " + responseCode);
        }
    } else {
        Class<? extends URLConnection> ucType = null;
        if (uc != null)
            ucType = uc.getClass();
        log.error("Failed opening login url: " + authLink + " returns: " + ucType);
        throw new LoginRefusedException("Login Failed, Unable to submit login url");
    }

    //throw new LoginRefusedException("Login Failed, unable to retrieve stage 1 url");
}

From source file:edu.utexas.quietplaces.services.PlacesUpdateService.java

/**
 * Polls the underlying service to return a list of places within the specified
 * radius of the specified Location./*  w  w  w .  j  a v a 2 s  .  c om*/
 *
 * @param location Location
 * @param radius   Radius
 */
protected void refreshPlaces(Location location, int radius, String page_token) {
    if (location == null) {
        Log.e(TAG, "Null location in refreshPlaces");
        return;
    }
    // Log to see if we'll be prefetching the details page of each new place.
    if (mobileData) {
        Log.d(TAG, "Not prefetching due to being on mobile");
    } else if (lowBattery) {
        Log.d(TAG, "Not prefetching due to low battery");
    }

    long currentTime = System.currentTimeMillis();
    URL url;

    String placeTypes = prefs.getString(PlacesConstants.SP_KEY_API_PLACE_TYPES,
            PlacesConstants.SP_KEY_API_PLACE_TYPES_DEFAULT);
    Log.v(TAG, "Doing places search with types: " + placeTypes);

    try {
        // Should be at most 6 decimal places for max cache usage, but 5 is fine too
        // https://developers.google.com/maps/documentation/business/articles/usage_limits

        String locationStr = String.format("%.5f,%.5f", location.getLatitude(), location.getLongitude());

        String baseURI = PlacesConstants.PLACES_LIST_BASE_URI;

        String placesFeed;
        if (page_token != null && page_token.length() > 0) {
            // Other params are actually ignored here.
            placesFeed = baseURI + PlacesConstants.getPlacesAPIKey(this, true) + "&pagetoken=" + page_token;
        } else {
            placesFeed = baseURI + "&types=" + placeTypes + "&location=" + locationStr + "&radius=" + radius
                    + PlacesConstants.getPlacesAPIKey(this, true);
        }
        url = new URL(placesFeed);

        Log.w(TAG, "HTTP request: " + url);

        // Open the connection
        URLConnection connection = url.openConnection();
        HttpsURLConnection httpConnection = (HttpsURLConnection) connection;
        int responseCode = httpConnection.getResponseCode();

        /*
                    if (connection.getUseCaches()) {
        Log.v(TAG, "Using HTTPS cache");
                    }
                    else {
        Log.v(TAG, "HTTPS cache is disabled");
                    }
        */

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // Use the XML Pull Parser to extract each nearby location.
            // TODO Replace the XML parsing to extract your own place list.
            InputStream in = httpConnection.getInputStream();

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser xpp = factory.newPullParser();

            int placesAddedThisRequest = 0;

            String next_page_token = "";

            xpp.setInput(in, null);
            int eventType = xpp.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("next_page_token")) {
                    next_page_token = xpp.nextText();
                } else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("result")) {
                    eventType = xpp.next();
                    String id = "";
                    String name = "";
                    String vicinity = "";
                    String types = "";
                    String locationLat = "";
                    String locationLng = "";
                    String viewport = "";
                    String icon = "";
                    String reference = "";
                    while (!(eventType == XmlPullParser.END_TAG && xpp.getName().equals("result"))) {
                        if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("name"))
                            name = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("vicinity"))
                            vicinity = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("type"))
                            types = types.equals("") ? xpp.nextText() : types + " " + xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("lat"))
                            locationLat = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("lng"))
                            locationLng = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("icon"))
                            icon = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("reference"))
                            reference = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("id"))
                            id = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG
                                && xpp.getName().equals("next_page_token"))
                            next_page_token = xpp.nextText();
                        eventType = xpp.next();
                    }

                    Location placeLocation = new Location(PlacesConstants.CONSTRUCTED_LOCATION_PROVIDER);
                    placeLocation.setLatitude(Double.valueOf(locationLat));
                    placeLocation.setLongitude(Double.valueOf(locationLng));

                    Log.v(TAG, "Found place: " + " location: " + location + " id: " + id + " name: " + name
                            + " vicinity: " + vicinity + " types: " + types + " ref: " + reference);

                    if (!next_page_token.equals("")) {
                        Log.e(TAG, "WARNING: unhandled next_page_token from Places search " + next_page_token);
                    }

                    // Add each new place to the Places Content Provider
                    addPlace(location, id, name, vicinity, types, placeLocation, viewport, icon, reference,
                            currentTime);
                    placesAddedThisRequest++;
                }
                eventType = xpp.next();
            }

            if (placesAddedThisRequest > 0) {
                Log.i(TAG, "Found " + placesAddedThisRequest + " places this request.");

                if (!next_page_token.equals("")) {
                    // TODO: we should check for INVALID_RESULT and retry after a shorter wait
                    // Currently, if this wait is too long, we waste time, but if it's too short, we don't get the next page.
                    Log.d(TAG, "Sleeping before fetching next page. Sleep interval (ms): "
                            + PlacesConstants.PLACES_NEXT_PAGE_INTERVAL_MS);
                    SystemClock.sleep(PlacesConstants.PLACES_NEXT_PAGE_INTERVAL_MS);
                    Log.i(TAG, "Fetching next page of places results.");
                    refreshPlaces(location, radius, next_page_token);
                }
            } else {
                Log.w(TAG, "Found 0 places this request.");
            }

            // Remove places from the PlacesDetailsContentProvider that aren't from this update.
            String where = PlaceDetailsContentProvider.KEY_LAST_UPDATE_TIME + " < " + currentTime;
            contentResolver.delete(PlacesContentProvider.CONTENT_URI, where, null);

            // Save the last update time and place to the Shared Preferences.
            prefsEditor.putFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LAT, (float) location.getLatitude());
            prefsEditor.putFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LNG, (float) location.getLongitude());
            prefsEditor.putLong(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_TIME, System.currentTimeMillis());
            sharedPreferenceSaver.savePreferences(prefsEditor, false);
            //prefsEditor.apply();
            //prefsEditor.commit();
        } else
            Log.e(TAG, responseCode + ": " + httpConnection.getResponseMessage());

    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    } catch (XmlPullParserException e) {
        Log.e(TAG, e.getMessage());
    } finally {
    }
}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

public HttpsURLConnection makeRequest(String verb, String url, @Nullable String postData, boolean json,
        boolean autoredirect, @Nullable Map<String, String> customHeaders)
        throws IOException, URISyntaxException {
    String currentUrl = url;/*  ww w. ja  v  a  2 s . c om*/
    for (int i = 0; i < 30; i++) // loop for handling redirect, using automatic redirect is not possible, because
                                 // all response headers must be catched
    {
        int code;
        HttpsURLConnection connection = null;
        try {
            logger.debug("Make request to {}", url);
            connection = (HttpsURLConnection) new URL(currentUrl).openConnection();
            connection.setRequestMethod(verb);
            connection.setRequestProperty("Accept-Language", "en-US");
            if (customHeaders == null || !customHeaders.containsKey("User-Agent")) {
                connection.setRequestProperty("User-Agent", userAgent);
            }
            connection.setRequestProperty("Accept-Encoding", "gzip");
            connection.setRequestProperty("DNT", "1");
            connection.setRequestProperty("Upgrade-Insecure-Requests", "1");
            if (customHeaders != null) {
                for (String key : customHeaders.keySet()) {
                    String value = customHeaders.get(key);
                    if (StringUtils.isNotEmpty(value)) {
                        connection.setRequestProperty(key, value);
                    }
                }
            }
            connection.setInstanceFollowRedirects(false);

            // add cookies
            URI uri = connection.getURL().toURI();

            if (customHeaders == null || !customHeaders.containsKey("Cookie")) {

                StringBuilder cookieHeaderBuilder = new StringBuilder();
                for (HttpCookie cookie : cookieManager.getCookieStore().get(uri)) {
                    if (cookieHeaderBuilder.length() > 0) {
                        cookieHeaderBuilder.append(";");
                    }
                    cookieHeaderBuilder.append(cookie.getName());
                    cookieHeaderBuilder.append("=");
                    cookieHeaderBuilder.append(cookie.getValue());
                    if (cookie.getName().equals("csrf")) {
                        connection.setRequestProperty("csrf", cookie.getValue());
                    }

                }
                if (cookieHeaderBuilder.length() > 0) {
                    String cookies = cookieHeaderBuilder.toString();
                    connection.setRequestProperty("Cookie", cookies);
                }
            }
            if (postData != null) {

                logger.debug("{}: {}", verb, postData);
                // post data
                byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
                int postDataLength = postDataBytes.length;

                connection.setFixedLengthStreamingMode(postDataLength);

                if (json) {
                    connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                } else {
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }
                connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
                if (verb == "POST") {
                    connection.setRequestProperty("Expect", "100-continue");
                }

                connection.setDoOutput(true);
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(postDataBytes);
                outputStream.close();
            }
            // handle result
            code = connection.getResponseCode();
            String location = null;

            // handle response headers
            Map<String, List<String>> headerFields = connection.getHeaderFields();
            for (Map.Entry<String, List<String>> header : headerFields.entrySet()) {
                String key = header.getKey();
                if (StringUtils.isNotEmpty(key)) {
                    if (key.equalsIgnoreCase("Set-Cookie")) {
                        // store cookie
                        for (String cookieHeader : header.getValue()) {
                            if (StringUtils.isNotEmpty(cookieHeader)) {

                                List<HttpCookie> cookies = HttpCookie.parse(cookieHeader);
                                for (HttpCookie cookie : cookies) {
                                    cookieManager.getCookieStore().add(uri, cookie);
                                }
                            }
                        }
                    }
                    if (key.equalsIgnoreCase("Location")) {
                        // get redirect location
                        location = header.getValue().get(0);
                        if (StringUtils.isNotEmpty(location)) {
                            location = uri.resolve(location).toString();
                            // check for https
                            if (location.toLowerCase().startsWith("http://")) {
                                // always use https
                                location = "https://" + location.substring(7);
                                logger.debug("Redirect corrected to {}", location);
                            }
                        }
                    }
                }
            }
            if (code == 200) {
                logger.debug("Call to {} succeeded", url);
                return connection;
            }
            if (code == 302 && location != null) {
                logger.debug("Redirected to {}", location);
                currentUrl = location;
                if (autoredirect) {
                    continue;
                }
                return connection;
            }
        } catch (IOException e) {

            if (connection != null) {
                connection.disconnect();
            }
            logger.warn("Request to url '{}' fails with unkown error", url, e);
            throw e;
        } catch (Exception e) {
            if (connection != null) {
                connection.disconnect();
            }
            throw e;
        }
        if (code != 200) {
            throw new HttpException(code,
                    verb + " url '" + url + "' failed: " + connection.getResponseMessage());
        }
    }
    throw new ConnectionException("Too many redirects");
}