Example usage for java.net HttpURLConnection setInstanceFollowRedirects

List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects

Introduction

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

Prototype

public void setInstanceFollowRedirects(boolean followRedirects) 

Source Link

Document

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

Usage

From source file:com.connectsdk.service.AirPlayService.java

@Override
public void displayImage(final String url, String mimeType, String title, String description, String iconSrc,
        final LaunchListener listener) {
    Util.runInBackground(new Runnable() {

        @Override//w w  w. j  a v  a 2 s. c  o  m
        public void run() {
            ResponseListener<Object> responseListener = new ResponseListener<Object>() {

                @Override
                public void onSuccess(Object response) {
                    LaunchSession launchSession = new LaunchSession();
                    launchSession.setService(AirPlayService.this);
                    launchSession.setSessionType(LaunchSessionType.Media);

                    Util.postSuccess(listener, new MediaLaunchObject(launchSession, AirPlayService.this));
                }

                @Override
                public void onError(ServiceCommandError error) {
                    Util.postError(listener, error);
                }
            };

            String uri = getRequestURL("photo");
            byte[] payload = null;

            try {
                URL imagePath = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) imagePath.openConnection();
                connection.setInstanceFollowRedirects(true);
                connection.setDoInput(true);
                connection.connect();

                int responseCode = connection.getResponseCode();
                boolean redirect = (responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                        || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                        || responseCode == HttpURLConnection.HTTP_SEE_OTHER);

                if (redirect) {
                    String newPath = connection.getHeaderField("Location");
                    URL newImagePath = new URL(newPath);
                    connection = (HttpURLConnection) newImagePath.openConnection();
                    connection.setInstanceFollowRedirects(true);
                    connection.setDoInput(true);
                    connection.connect();
                }

                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                payload = stream.toByteArray();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
                    AirPlayService.this, uri, payload, responseListener);
            request.setHttpMethod(ServiceCommand.TYPE_PUT);
            request.send();
        }
    });
}

From source file:com.licryle.httpposter.HttpPoster.java

/**
 * Opens a connection to the POST end point specified in the mConf
 * {@link HttpConfiguration} and sends the content of mEntity. Attempts to
 * read the answer from the server after the POST Request.
 * //from ww  w  .  ja  v a2s.c  o  m
 * @param mConf The {@link HttpConfiguration} of the request.
 * @param mEntity The Entity to send in the HTTP Post. Should be built using
 *                {@link #_buildEntity}.
 *
 * @return The result of the HTTP Post request. Either #SUCCESS,
 * #FAILURE_CONNECTION, #FAILURE_TRANSFER, #FAILURE_RESPONSE,
 * #FAILURE_MALFORMEDURL.
 *
 * @see HttpConfiguration
 * @see _ProgressiveEntity
 */
protected Long _httpPost(HttpConfiguration mConf, _ProgressiveEntity mEntity) {
    Log.d("HttpPoster", String.format("_httpPost: Entering Instance %d", _iInstanceId));

    /******** Open request ********/
    try {
        HttpURLConnection mConn = (HttpURLConnection) mConf.getEndPoint().openConnection();

        mConn.setRequestMethod("POST");
        mConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + mConf.getHTTPBoundary());

        mConn.setDoInput(true);
        mConn.setDoOutput(true);
        mConn.setUseCaches(false);
        mConn.setReadTimeout(mConf.getReadTimeout());
        mConn.setConnectTimeout(mConf.getConnectTimeout());
        mConn.setInstanceFollowRedirects(false);

        mConn.connect();

        Log.d("HttpPoster", String.format("_httpPost: Connected for Instance %d", _iInstanceId));

        try {
            /********** Write request ********/
            _dispatchOnStartTransfer();

            Log.d("HttpPoster", String.format("_httpPost: Sending for Instance %d", _iInstanceId));

            mEntity.writeTo(mConn.getOutputStream());
            mConn.getOutputStream().flush();
            mConn.getOutputStream().close();

            _iResponseCode = mConn.getResponseCode();
            try {
                Log.d("HttpPoster", String.format("_httpPost: Reading for Instance %d", _iInstanceId));

                _readServerAnswer(mConn.getInputStream());
                return SUCCESS;
            } catch (IOException e) {
                return FAILURE_RESPONSE;
            }
        } catch (Exception e) {
            Log.d("HTTPParser", e.getMessage());
            e.printStackTrace();

            return FAILURE_TRANSFER;
        } finally {
            if (mConn != null) {
                Log.d("HttpPoster", String.format("_httpPost: Disconnecting Instance %d", _iInstanceId));

                mConn.disconnect();
            }
        }
    } catch (Exception e) {
        return FAILURE_CONNECTION;
    }
}

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

public String doRedirect(String urlRedirect) {
    // android.os.Debug.waitForDebugger();
    try {//w  w w .j  av  a  2 s. c  o  m

        Log.d(TAG, "mOcp.m_redirect_uri=" + mOcp.m_redirect_uri);

        Log.d(TAG, "urlRedirect=" + urlRedirect);

        // with server phpOIDC, check for '#'
        if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?"))
                || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) {
            Log.d(TAG, "doRedirect : in check");

            String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&");
            String code = "";
            String state = "";
            String state_key = "state";
            for (int i = 0; i < params.length; i++) {
                String param = params[i];
                int idxEqual = param.indexOf('=');
                if (idxEqual >= 0) {
                    String key = param.substring(0, idxEqual);
                    String value = param.substring(idxEqual + 1);
                    if (key.startsWith("code"))
                        code = value;
                    if (key.startsWith("state"))
                        state = value;
                    if (key.startsWith("session_state")) {
                        state = value;
                        state_key = "session_state";
                    }
                }
            }

            // display code and state
            Logd(TAG, "doRedirect => code: " + code + " / state: " + state);

            // doRepost(code,state);
            if (code.length() > 0) {

                // get token_endpoint endpoint
                String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url);

                Log.d(TAG, "token_endpoint=" + token_endpoint);

                if (isEmpty(token_endpoint)) {
                    Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url);
                    return null;
                }

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                HttpURLConnection huc = getHUC(token_endpoint);
                huc.setInstanceFollowRedirects(false);

                if (mUsePrivateKeyJWT) {
                    nameValuePairs.add(new BasicNameValuePair("client_assertion_type",
                            "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));
                    String client_assertion = secureProxy.getPrivateKeyJwt(token_endpoint);
                    Logd(TAG, "client_assertion: " + client_assertion);
                    nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion));
                } else {
                    huc.setRequestProperty("Authorization", "Basic " + secureProxy.getClientSecretBasic());
                }

                huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                huc.setDoOutput(true);
                huc.setChunkedStreamingMode(0);

                OutputStream os = huc.getOutputStream();
                OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8");
                BufferedWriter writer = new BufferedWriter(out);

                nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
                Logd(TAG, "code: " + code);
                nameValuePairs.add(new BasicNameValuePair("code", code));
                nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri));
                Logd(TAG, "redirect_uri" + mOcp.m_redirect_uri);
                if (state != null && state.length() > 0)
                    nameValuePairs.add(new BasicNameValuePair(state_key, state));

                // write URL encoded string from list of key value pairs
                writer.write(getQuery(nameValuePairs));
                writer.flush();
                writer.close();
                out.close();
                os.close();

                Logd(TAG, "doRedirect => before connect");
                Logd(TAG, "huc=" + huc.toString());
                huc.connect();
                Logd(TAG, "huc2=" + huc.getContentEncoding());
                int responseCode = huc.getResponseCode();
                System.out.println("2 - code " + responseCode);
                Log.d(TAG, "doRedirect => responseCode " + responseCode);
                InputStream in = null;
                try {
                    in = new BufferedInputStream(huc.getInputStream());
                } catch (IOException ioe) {
                    sysout("io exception: " + huc.getErrorStream());
                }
                if (in != null) {
                    String result = convertStreamToString(in);
                    // now you have the string representation of the HTML request
                    in.close();

                    Logd(TAG, "doRedirect: " + result);

                    // save as static for now
                    return result;

                } else {
                    Logd(TAG, "doRedirect null");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.commonsware.android.EMusicDownloader.SingleBook.java

public void sampleButtonPressed(View button) {

    Log.d("EMD - ", "Attempting to play sample");

    if (sampleURL.contains("sample")) {
        final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.getting_sample_loation),
                true, true);/*  ww w .  j av a2 s  .  c om*/

        Thread t5 = new Thread() {
            public void run() {

                String addresstemp = "";

                try {
                    URL u = new URL(sampleURL);
                    HttpURLConnection c = (HttpURLConnection) u.openConnection();
                    c.setRequestMethod("GET");
                    //c.setDoOutput(true);
                    c.setFollowRedirects(true);
                    c.setInstanceFollowRedirects(true);
                    c.connect();
                    InputStream in = c.getInputStream();

                    InputStreamReader inputreader = new InputStreamReader(in);
                    BufferedReader buffreader = new BufferedReader(inputreader);

                    String line;

                    // read every line of the file into the line-variable, on line at the time
                    while ((line = buffreader.readLine()).length() > 0) {
                        //Log.d("EMD - ","Read line"+line);
                        if (line.contains(".mp3") || line.contains("samples.emusic")
                                || line.contains("samples.nl.emusic")) {
                            addresstemp = line;
                            //Log.d("EMD - ","Found MP3 Address "+addresstemp);
                            mp3Address = addresstemp;
                            if (!vKilled && dialog.isShowing()) {
                                handlerPlay.sendEmptyMessage(0);
                            }
                            if (dialog.isShowing()) {
                                dialog.dismiss();
                            }
                        }
                    }

                    in.close();
                    c.disconnect();
                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    }
                } catch (Exception ef) {
                    Log.d("EMD - ", "Getting mp3 address failed ");
                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    }
                }
            }
        };
        t5.start();
    } else {
        Toast.makeText(thisActivity, R.string.no_sample_available, Toast.LENGTH_SHORT).show();
    }
}

From source file:com.plancake.api.client.PlancakeApiClient.java

/**
 * @param String request// w  w  w .ja va  2  s .  c  om
 * @param String httpMethod
 * @return String
 */
private String getResponse(String request, String httpMethod)
        throws MalformedURLException, IOException, PlancakeApiException {
    if (!(httpMethod.equals("GET")) && !(httpMethod.equals("POST"))) {
        throw new PlancakeApiException("httpMethod must be either GET or POST");
    }

    String urlParameters = "";

    if (httpMethod == "POST") {
        String[] requestParts = request.split("\\?");
        request = requestParts[0];
        urlParameters = requestParts[1];
    }

    URL url = new URL(request);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod(httpMethod);
    if (httpMethod == "POST") {
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    } else {
        connection.setRequestProperty("Content-Type", "text/plain");
    }
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
    connection.setUseCaches(false);
    connection.connect();

    if (httpMethod == "POST") {
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
    }

    StringBuffer text = new StringBuffer();
    InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());
    BufferedReader buff = new BufferedReader(in);
    String line = buff.readLine();
    while (line != null) {
        text.append(line + "\n");
        line = buff.readLine();
    }
    String response = text.toString();

    if (response.length() == 0) {
        throw new PlancakeApiException("the response is empty");
    }

    connection.disconnect();
    return response;
}

From source file:net.caseif.flint.steel.lib.net.gravitydevelopment.updater.Updater.java

private URL followRedirects(String location) throws IOException {
    URL resourceUrl, base, next;//  w ww  .j a  va  2 s  .  c  o m
    HttpURLConnection conn;
    String redLoc;
    while (true) {
        resourceUrl = new URL(location);
        conn = (HttpURLConnection) resourceUrl.openConnection();

        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestProperty("User-Agent", "Mozilla/5.0...");

        switch (conn.getResponseCode()) {
        case HttpURLConnection.HTTP_MOVED_PERM:
        case HttpURLConnection.HTTP_MOVED_TEMP:
            redLoc = conn.getHeaderField("Location");
            base = new URL(location);
            next = new URL(base, redLoc); // Deal with relative URLs
            location = next.toExternalForm();
            continue;
        }
        break;
    }
    return conn.getURL();
}

From source file:org.runnerup.export.RuntasticUploader.java

@Override
public Status connect() {
    Exception ex = null;//ww w  . j a v a 2  s  .  com
    HttpURLConnection conn = null;
    formValues.clear();

    Status s = Status.NEED_AUTH;
    s.authMethod = AuthMethod.USER_PASS;
    if (username == null || password == null) {
        return s;
    }

    System.out.println("userId: " + userId + ", authToken: " + authToken);
    if (userId != null && authToken != null) {
        return Status.OK;
    }

    cookies.clear();

    try {
        /**
         * connect to START_URL to get cookies/formValues
         */
        conn = (HttpURLConnection) new URL(START_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        addRequestHeaders(conn);
        {
            //                int responseCode = conn.getResponseCode();
            //                String amsg = conn.getResponseMessage();
            getCookies(conn);
            getFormValues(conn);
            authToken = formValues.get("authenticity_token");
        }
        conn.disconnect();

        if (authToken == null)
            return Status.ERROR;

        /**
         * Then login using a post
         */
        FormValues kv = new FormValues();
        kv.put("user[email]", username);
        kv.put("user[password]", password);
        kv.put("authenticity-token", authToken);

        conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        addRequestHeaders(conn);
        conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        String url2 = null;
        {
            OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
            kv.write(wr);
            wr.flush();
            wr.close();
            // int responseCode = conn.getResponseCode();
            // String amsg = conn.getResponseMessage();
            getCookies(conn);
            InputStream in = new BufferedInputStream(conn.getInputStream());
            JSONObject ret = parse(in);
            if (ret != null && ret.has("success") && ret.getBoolean("success")) {
                Matcher matcher = Patterns.WEB_URL.matcher(ret.getString("update"));
                while (matcher.find()) {
                    String tmp = matcher.group();
                    final String users = "/users/";
                    if (tmp.contains(users)) {
                        int i = tmp.indexOf(users) + users.length();
                        int i2 = tmp.indexOf('/', i);
                        if (i2 > 0)
                            url2 = tmp.substring(0, i2);
                        else
                            url2 = tmp;

                        if (url2 != null)
                            break;
                    }
                }
            }
            System.out.println("found url2: " + url2);
            conn.disconnect();
        }

        if (url2 == null) {
            return s;
        }

        {
            url2 = url2 + "?authenticity_token=" + URLEncode(authToken);
            conn = (HttpURLConnection) new URL(url2).openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Host", "www.runtastic.com");
            conn.addRequestProperty("Accept", "application/json");
            InputStream in = new BufferedInputStream(conn.getInputStream());
            getCookies(conn);
            JSONObject ret = parse(in);
            userId = ret.getJSONObject("user").getInt("id");
            conn.disconnect();
        }

        if (userId != null && authToken != null) {
            return Status.OK;
        }
    } catch (MalformedURLException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    }

    if (conn != null)
        conn.disconnect();

    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

From source file:org.runnerup.export.RuntasticSynchronizer.java

@Override
public Status connect() {
    Exception ex = null;//from w w w .  j a v a  2  s .  c o m
    HttpURLConnection conn = null;
    formValues.clear();

    Status s = Status.NEED_AUTH;
    s.authMethod = AuthMethod.USER_PASS;
    if (username == null || password == null) {
        return s;
    }

    Log.i(getName(), "userId: " + userId + ", authToken: " + authToken);
    if (userId != null && authToken != null) {
        return Status.OK;
    }

    cookies.clear();

    try {
        /**
         * connect to START_URL to get cookies/formValues
         */
        conn = (HttpURLConnection) new URL(START_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        addRequestHeaders(conn);
        {
            //                int responseCode = conn.getResponseCode();
            //                String amsg = conn.getResponseMessage();
            getCookies(conn);
            getFormValues(conn);
            authToken = formValues.get("authenticity_token");
        }
        conn.disconnect();

        if (authToken == null)
            return Status.ERROR;

        /**
         * Then login using a post
         */
        FormValues kv = new FormValues();
        kv.put("user[email]", username);
        kv.put("user[password]", password);
        kv.put("authenticity-token", authToken);
        kv.put("grant_type", "password");

        conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        addRequestHeaders(conn);
        conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        String url2 = null;
        {
            OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
            kv.write(wr);
            wr.flush();
            wr.close();
            // int responseCode = conn.getResponseCode();
            // String amsg = conn.getResponseMessage();
            getCookies(conn);
            InputStream in = new BufferedInputStream(conn.getInputStream());
            JSONObject ret = SyncHelper.parse(in);
            if (ret != null && ret.has("success") && ret.getBoolean("success")) {
                Matcher matcher = Patterns.WEB_URL.matcher(ret.getString("update"));
                while (matcher.find()) {
                    String tmp = matcher.group();
                    final String users = "/users/";
                    if (tmp.contains(users)) {
                        int i = tmp.indexOf(users) + users.length();
                        int i2 = tmp.indexOf('/', i);
                        if (i2 > 0)
                            url2 = tmp.substring(0, i2);
                        else
                            url2 = tmp;

                        if (url2 != null)
                            break;
                    }
                }
            }
            Log.i(getName(), "found url2: " + url2);
            conn.disconnect();
        }

        if (url2 == null) {
            return s;
        }

        {
            url2 = url2 + "?authenticity_token=" + SyncHelper.URLEncode(authToken);
            conn = (HttpURLConnection) new URL(url2).openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod(RequestMethod.GET.name());
            conn.setRequestProperty("Host", "www.runtastic.com");
            conn.addRequestProperty("Accept", "application/json");
            InputStream in = new BufferedInputStream(conn.getInputStream());
            getCookies(conn);
            JSONObject ret = SyncHelper.parse(in);
            userId = ret.getJSONObject("user").getInt("id");
            conn.disconnect();
        }

        if (userId != null && authToken != null) {
            return Status.OK;
        }
    } catch (MalformedURLException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    }

    if (conn != null)
        conn.disconnect();

    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

From source file:org.piwik.SimplePiwikTracker.java

/**
 * Sends the request to the PIWIK-Server.
 * /*  w  ww  .  ja v a 2s.  c  o m*/
 * @param destination the built request string.
 * @return ResponseData
 * @throws PiwikException
 */
public final ResponseData sendRequest(final URL destination) throws PiwikException {
    ResponseData responseData = null;
    if (destination != null) {
        try {
            LOGGER.log(Level.FINE, "try to open piwik request url: {0}", destination);

            HttpURLConnection connection = (HttpURLConnection) destination.openConnection();
            connection.setInstanceFollowRedirects(false);
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(600);
            connection.setRequestProperty("User-Agent", userAgent);
            connection.setRequestProperty("Accept-Language", language);
            if (requestCookie != null) {
                connection.setRequestProperty("Cookie",
                        requestCookie.getName() + "=" + requestCookie.getValue());
            }

            responseData = new ResponseData(connection);
            List<Cookie> cookies = responseData.getCookies();
            if (cookies.size() > 0) {
                if (cookies.get(cookies.size() - 1).getName().lastIndexOf("XDEBUG") == -1
                        && cookies.get(cookies.size() - 1).getValue().lastIndexOf("XDEBUG") == -1) {
                    requestCookie = cookies.get(cookies.size() - 1);
                }
            }

            if (connection.getResponseCode() != HttpServletResponse.SC_OK) {
                LOGGER.log(Level.WARNING, "Warning:{0} {1}",
                        new Object[] { connection.getResponseCode(), connection.getResponseMessage() });
                throw new PiwikException(
                        "error:" + connection.getResponseCode() + " " + connection.getResponseMessage());
            }

            connection.disconnect();
        } catch (final IOException e) {
            throw new PiwikException("Error while sending request to piwik", e);
        }
    }
    return responseData;
}

From source file:de.gebatzens.sia.SiaAPI.java

public APIResponse doRequest(String url, JSONObject request) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(BuildConfig.BACKEND_SERVER + url).openConnection();

    con.setRequestProperty("User-Agent",
            "SchulinfoAPP/" + BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + " "
                    + BuildConfig.BUILD_TYPE + " Android " + Build.VERSION.RELEASE + " " + Build.PRODUCT + ")");
    con.setRequestProperty("Accept-Encoding", "gzip");
    con.setConnectTimeout(3000);/*  w  w w  .j a  va 2  s . co m*/
    con.setRequestMethod(request == null ? "GET" : "POST");
    con.setInstanceFollowRedirects(false);

    if (request != null) {
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json");
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(request.toString());
        wr.flush();
        wr.close();
    }

    if (BuildConfig.DEBUG)
        Log.d("ggvp", "connection to " + con.getURL() + " established");

    InputStream in = con.getResponseCode() != 200 ? con.getErrorStream() : con.getInputStream();
    String encoding = con.getHeaderField("Content-Encoding");
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        in = new GZIPInputStream(in);
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String response = "";
    String line = "";
    while ((line = reader.readLine()) != null)
        response += line;
    JSONObject json = null;
    try {
        json = new JSONObject(response);
        String state = json.getString("state");
        Object data = json.opt("data");
        String reason = json.optString("reason", "");

        Log.d("ggvp", "received state " + state + " " + con.getResponseCode() + " reason: " + reason);

        return new APIResponse(state.equals("succeeded") ? APIState.SUCCEEDED : APIState.FAILED, data, reason);

    } catch (JSONException e) {
        Log.e("ggvp", e.toString());
        e.printStackTrace();
        return new APIResponse(APIState.FAILED);
    }

}