Example usage for javax.net.ssl HttpsURLConnection getResponseCode

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

Introduction

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

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:org.georchestra.console.ReCaptchaV2.java

/**
 *
 * @param url//from w  w  w  .  ja  v  a  2  s  .  co  m
 * @param privateKey
 * @param gRecaptchaResponse
 *
 * @return true if validaded on server side by google, false in case of error or if an exception occurs
 */
public boolean isValid(String url, String privateKey, String gRecaptchaResponse) {
    boolean isValid = false;

    try {
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        // add request header
        con.setRequestMethod("POST");
        String postParams = "secret=" + privateKey + "&response=" + gRecaptchaResponse;

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();

        if (LOG.isDebugEnabled()) {
            int responseCode = con.getResponseCode();
            LOG.debug("\nSending 'POST' request to URL : " + url);
            LOG.debug("Post parameters : " + postParams);
            LOG.debug("Response Code : " + responseCode);
        }

        // getResponse
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        LOG.debug(response.toString());

        JSONObject captchaResponse;
        try {
            captchaResponse = new JSONObject(response.toString());

            if (captchaResponse.getBoolean("success")) {
                isValid = true;
            } else {
                // Error in response
                LOG.info("The user response to recaptcha is not valid. The error message is '"
                        + captchaResponse.getString("error-codes")
                        + "' - see Error Code Reference at https://developers.google.com/recaptcha/docs/verify.");
            }
        } catch (JSONException e) {
            // Error in response
            LOG.error("Error while parsing ReCaptcha JSON response", e);
        }
    } catch (IOException e) {
        LOG.error("An error occured when trying to contact google captchaV2", e);
    }

    return isValid;
}

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./*from  w ww. j av  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:com.fastbootmobile.twofactorauthdemo.MainActivity.java

protected void registerWithBackend() {

    final SharedPreferences pref = this.getSharedPreferences(OwnPushClient.PREF_PUSH, Context.MODE_PRIVATE);

    Thread httpThread = new Thread(new Runnable() {

        private String TAG = "httpThread";
        private String ENDPOINT = "https://otp.demo.ownpush.com/push/register";

        @Override//from  w  ww  .ja  v  a  2 s  . c  om
        public void run() {
            URL urlObj;

            try {
                urlObj = new URL(ENDPOINT);

                String install_id = pref.getString(OwnPushClient.PREF_PUBLIC_KEY, null);

                if (install_id == null) {
                    return;
                }

                String mPostData = "push_id=" + install_id;
                HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();

                con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
                con.setRequestProperty("Accept", "*/*");
                con.setDoInput(true);
                con.setRequestMethod("POST");
                con.getOutputStream().write(mPostData.getBytes());
                con.connect();
                int http_status = con.getResponseCode();

                if (http_status != 200) {
                    Log.e(TAG, "ERROR IN HTTP REPONSE : " + http_status);
                    return;
                }

                InputStream stream;
                stream = con.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                String data = sb.toString();

                if (data.contains("device_uid")) {
                    JSONObject json = new JSONObject(data);
                    String device_id = json.getString("device_uid");
                    pref.edit().putString("device_uid", device_id).commit();
                    Log.d(TAG, "GOT DEVICE UID OF " + device_id);

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            updateUI();
                        }
                    });

                }

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

    httpThread.start();
}

From source file:org.wso2.carbon.sample.service.EventsManagerService.java

public String performPostCall(String requestURL, Map<String, String> postDataParams)
        throws HttpException, IOException {

    URL url;/*w  w  w. j a v a  2s. c  o m*/
    String response = "";

    url = new URL(requestURL);

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(15000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getPostDataString(postDataParams));

    writer.flush();
    writer.close();
    os.close();
    int responseCode = conn.getResponseCode();

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = br.readLine()) != null) {
            response += line;
        }
    } else {
        response = "";
        throw new HttpException(responseCode + "");
    }

    return response;
}

From source file:org.openhab.binding.zonky.internal.ZonkyBinding.java

private String sendJsonRequest(String uri) {
    String url = null;// w w w.j a  v  a 2 s  .co  m

    logger.debug("sending uri request: {}", uri);
    try {
        //login
        url = ZONKY_URL + uri;

        URL cookieUrl = new URL(url);
        HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();
        setupConnectionDefaults(connection);
        connection.setRequestProperty("Authorization", "Bearer " + token);

        if (connection.getResponseCode() != 200) {
            logger.error("Got response code: {}", connection.getResponseCode());
            return null;
        }

        return readResponse(connection);
    } catch (MalformedURLException e) {
        logger.error("The URL '{}' is malformed", url, e);
    } catch (Exception e) {
        logger.error("Cannot get Zonky wallet response", e);
    }
    return null;
}

From source file:com.microsoft.valda.oms.OmsAppender.java

private void sendLog(LoggingEvent event)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException {
    //create JSON message
    JSONObject obj = new JSONObject();
    obj.put("LOGBACKLoggerName", event.getLoggerName());
    obj.put("LOGBACKLogLevel", event.getLevel().toString());
    obj.put("LOGBACKMessage", event.getFormattedMessage());
    obj.put("LOGBACKThread", event.getThreadName());
    if (event.getCallerData() != null && event.getCallerData().length > 0) {
        obj.put("LOGBACKCallerData", event.getCallerData()[0].toString());
    } else {/*w  ww  .  j a va 2s  .c  o m*/
        obj.put("LOGBACKCallerData", "");
    }
    if (event.getThrowableProxy() != null) {
        obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
    } else {
        obj.put("LOGBACKStackTrace", "");
    }
    if (inetAddress != null) {
        obj.put("LOGBACKIPAddress", inetAddress.getHostAddress());
    } else {
        obj.put("LOGBACKIPAddress", "0.0.0.0");
    }
    String json = obj.toJSONString();

    String Signature = "";
    String encodedHash = "";
    String url = "";

    // Todays date input for OMS Log Analytics
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String timeNow = dateFormat.format(calendar.getTime());

    // String for signing the key
    String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs";
    byte[] decodedBytes = Base64.decodeBase64(sharedKey);
    Mac hasher = Mac.getInstance("HmacSHA256");
    hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256"));
    byte[] hash = hasher.doFinal(stringToSign.getBytes());

    encodedHash = DatatypeConverter.printBase64Binary(hash);
    Signature = "SharedKey " + customerId + ":" + encodedHash;

    url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";
    URL objUrl = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Log-Type", logType);
    con.setRequestProperty("x-ms-date", timeNow);
    con.setRequestProperty("Authorization", Signature);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(json);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        throw new HTTPException(responseCode);
    }
}

From source file:com.illusionaryone.GameWispAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String methodType, String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    OutputStream outputStream = null;
    URL urlRaw;//ww  w  .  ja v  a  2s  .  c o m
    HttpsURLConnection urlConn;
    String jsonText = "";

    if (sAccessToken.length() == 0) {
        if (!noAccessWarning) {
            com.gmt2001.Console.err.println(
                    "GameWispAPIv1: Attempting to use GameWisp API without key. Disabling the GameWisp module.");
            PhantomBot.instance().getDataStore().set("modules", "./handlers/gameWispHandler.js", "false");
            noAccessWarning = true;
        }
        JSONStringer jsonObject = new JSONStringer();
        return (new JSONObject(jsonObject.object().key("result").object().key("status").value(-1).endObject()
                .endObject().toString()));
    }

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod(methodType);
        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");

        if (methodType.equals("POST")) {
            urlConn.setDoOutput(true);
            urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        } else {
            urlConn.addRequestProperty("Content-Type", "application/json");
        }

        urlConn.connect();

        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, methodType, urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "JSONException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GameWispAPIv1::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "...");
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(),
                        "");
                com.gmt2001.Console.err
                        .println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
            }
    }

    return (jsonResult);
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

@Override
public int checkConnection(String testRequest) {
    try {//from   w  ww  .  jav  a  2s  .  c o  m
        HttpsURLConnection connection = getConnection(testRequest, connectTimeout, readTimeout);
        if (connection != null) {
            connection.connect();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                if (IOUtils.toString(connection.getInputStream()).contains("Authentication failed")) {
                    return ConnectionManager.AUTHENTIFICATION_PROBLEM;
                }
            }
            connection.disconnect();
            return connection.getResponseCode();
        } else {
            return ConnectionManager.GENERAL_EXCEPTION;
        }
    } catch (SocketTimeoutException e) {
        return ConnectionManager.SOCKET_TIMEOUT_EXCEPTION;
    } catch (java.net.ConnectException e) {
        return ConnectionManager.CONNECTION_EXCEPTION;
    } catch (MalformedURLException e) {
        return ConnectionManager.MALFORMED_URL_EXCEPTION;
    } catch (java.net.UnknownHostException e) {
        return ConnectionManager.UNKNOWN_HOST_EXCEPTION;
    } catch (IOException e) {
        return ConnectionManager.GENERAL_EXCEPTION;
    }
}

From source file:in.rab.ordboken.NeClient.java

private String fetchMainSitePage(String pageUrl) throws IOException, LoginException, ParserException {
    URL url = new URL(pageUrl);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setInstanceFollowRedirects(false);
    urlConnection.connect();//from w  w  w .  j a va  2s  . c om

    int response;

    try {
        response = urlConnection.getResponseCode();
    } catch (IOException e) {
        urlConnection.disconnect();
        throw e;
    }

    if (response == 302) {
        urlConnection.disconnect();

        try {
            loginMainSite();
        } catch (EOFException e) {
            // Same EOFException as on token refreshes. Seems to be a POST thing.
            loginMainSite();
        }

        url = new URL(pageUrl);
        urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setInstanceFollowRedirects(false);
        urlConnection.connect();

        try {
            response = urlConnection.getResponseCode();
        } catch (IOException e) {
            urlConnection.disconnect();
            throw e;
        }
    }

    try {
        if (response != 200) {
            throw new ParserException("Unable to get page: " + response);
        }

        return inputStreamToString(urlConnection.getInputStream());
    } finally {
        urlConnection.disconnect();
    }
}

From source file:net.indialend.web.component.GCMComponent.java

public void setMessage(User user, String deactivate) {

    try {/*from w w w .j  a  v a2  s.c  om*/
        URL obj = new URL(serviceUrl);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "key=" + API_KEY);

        String urlParameters = "{" + "   \"data\": {" + "     \"deactivate\": \"" + deactivate + "\"," + "   },"
                + "   \"to\": \"" + user.getGcmToken() + "\"" + " }";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(urlParameters.getBytes("UTF-8"));
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + serviceUrl);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}