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:fi.cosky.sdk.API.java

private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass,
        Object object, HashMap<String, String> headers) throws IOException {
    URL serverAddress;/*from ww w . j a  v a  2 s . com*/
    HttpURLConnection connection;
    BufferedReader br;
    String result = "";
    try {
        serverAddress = new URL(url);
        connection = (HttpURLConnection) serverAddress.openConnection();
        connection.setInstanceFollowRedirects(false);
        boolean doOutput = doOutput(verb);
        connection.setDoOutput(doOutput);
        connection.setRequestMethod(method(verb));
        connection.setRequestProperty("Authorization", headers.get("authorization"));
        connection.addRequestProperty("Accept", "application/json");

        if (doOutput) {
            connection.addRequestProperty("Content-Length", "0");
            OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream());
            os.write("");
            os.flush();
            os.close();
        }
        connection.connect();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER
                || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            Link location = parseLocationLinkFromString(connection.getHeaderField("Location"));
            Link l = new Link("self", "/tokens", "GET", "", true);
            ArrayList<Link> links = new ArrayList<Link>();
            links.add(l);
            links.add(location);
            ResponseData data = new ResponseData();
            data.setLocation(location);
            data.setLinks(links);
            return (T) data;
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            System.out.println("Authentication expired: " + connection.getResponseMessage());
            if (retry && this.tokenData != null) {
                retry = false;
                this.tokenData = null;
                if (authenticate()) {
                    System.out.println(
                            "Reauthentication success, will continue with " + verb + " request on " + url);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                }
            } else
                throw new IOException(
                        "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API");
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST
                && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) {
            System.out.println("ErrorCode: " + connection.getResponseCode() + " "
                    + connection.getResponseMessage() + " " + url + ", verb: " + verb);

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class);
        } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
            if (retry) {
                System.out.println("Server responded with internal server error, trying again in "
                        + RETRY_WAIT_TIME + " msec.");
                try {
                    retry = false;
                    Thread.sleep(RETRY_WAIT_TIME);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                } catch (InterruptedException e) {

                }
            } else {
                System.out.println("Server responded with internal server error, please contact dev@nfleet.fi");
            }

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw new IOException(errorString);
        }

        result = readDataFromConnection(connection);
    } catch (MalformedURLException e) {
        throw e;
    } catch (ProtocolException e) {
        throw e;
    } catch (UnsupportedEncodingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
    return (T) gson.fromJson(result, tClass);
}

From source file:org.appcelerator.titanium.util.TiUIHelper.java

/**
 * To get the redirected Uri/*from   w  ww  . j a  va 2  s  .  co  m*/
 * @param Uri
 */
public static Uri getRedirectUri(Uri mUri) throws MalformedURLException, IOException {
    if (!TiC.HONEYCOMB_OR_GREATER && ("http".equals(mUri.getScheme()) || "https".equals(mUri.getScheme()))) {
        // Media player doesn't handle redirects, try to follow them
        // here. (Redirects work fine without this in ICS.)
        while (true) {
            // java.net.URL doesn't handle rtsp
            if (mUri.getScheme() != null && mUri.getScheme().equals("rtsp"))
                break;

            URL url = new URL(mUri.toString());
            HttpURLConnection cn = (HttpURLConnection) url.openConnection();
            cn.setInstanceFollowRedirects(false);
            String location = cn.getHeaderField("Location");
            if (location != null) {
                String host = mUri.getHost();
                int port = mUri.getPort();
                String scheme = mUri.getScheme();
                mUri = Uri.parse(location);
                if (mUri.getScheme() == null) {
                    // Absolute URL on existing host/port/scheme
                    if (scheme == null) {
                        scheme = "http";
                    }
                    String authority = port == -1 ? host : host + ":" + port;
                    mUri = mUri.buildUpon().scheme(scheme).encodedAuthority(authority).build();
                }
            } else {
                break;
            }
        }
    }
    return mUri;
}

From source file:uk.ac.gate.cloud.client.RestClient.java

/**
 * Perform an HTTP GET request on a URL whose response is expected to
 * be a 3xx redirection, and return the target redirection URL.
 * //from  w w w.  j a v  a  2s  .c o m
 * @param source the URL to request (relative URLs will resolve
 *          against the {@link #getBaseUrl() base URL}).
 * @return the URL returned by the "Location" header of the
 *         redirection response.
 * @throws RestClientException if an exception occurs during
 *           processing, or the server returns a 4xx or 5xx error
 *           response (in which case the response JSON message will be
 *           available as a {@link JsonNode} in the exception), or if
 *           the response was not a 3xx redirection.
 */
public URL getRedirect(URL source) throws RestClientException {
    try {
        HttpURLConnection connection = (HttpURLConnection) source.openConnection();
        connection.setRequestMethod("GET");
        if (authorizationHeader != null) {
            connection.setRequestProperty("Authorization", authorizationHeader);
        }
        connection.setRequestProperty("Accept", "application/json");
        connection.setInstanceFollowRedirects(false);
        int responseCode = connection.getResponseCode();
        // make sure we read any response content
        readResponseOrError(connection, new TypeReference<JsonNode>() {
        }, false);
        if (responseCode >= 300 && responseCode < 400) {
            // it was a redirect
            String redirectUrl = connection.getHeaderField("Location");
            return new URL(redirectUrl);
        } else {
            throw new RestClientException("Expected redirect but got " + responseCode);
        }
    } catch (IOException e) {
        throw new RestClientException(e);
    }
}

From source file:com.google.glassware.NotifyServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Respond with OK and status 200 in a timely fashion to prevent redelivery
    response.setContentType("text/html");
    Writer writer = response.getWriter();
    writer.append("OK");
    writer.close();//ww w . j  a  v a 2 s  .co m

    // Get the notification object from the request body (into a string so we
    // can log it)
    BufferedReader notificationReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String notificationString = "";

    String responseStringForFaceDetection = null;
    // Count the lines as a very basic way to prevent Denial of Service attacks
    int lines = 0;
    String line;
    while ((line = notificationReader.readLine()) != null) {
        notificationString += line;
        lines++;

        // No notification would ever be this long. Something is very wrong.
        if (lines > 1000) {
            throw new IOException("Attempted to parse notification payload that was unexpectedly long.");
        }
    }
    notificationReader.close();

    LOG.info("got raw notification " + notificationString);

    JsonFactory jsonFactory = new JacksonFactory();

    // If logging the payload is not as important, use
    // jacksonFactory.fromInputStream instead.
    Notification notification = jsonFactory.fromString(notificationString, Notification.class);

    LOG.info("Got a notification with ID: " + notification.getItemId());

    // Figure out the impacted user and get their credentials for API calls
    String userId = notification.getUserToken();
    Credential credential = AuthUtil.getCredential(userId);
    Mirror mirrorClient = MirrorClient.getMirror(credential);

    if (notification.getCollection().equals("locations")) {
        LOG.info("Notification of updated location");
        Mirror glass = MirrorClient.getMirror(credential);
        // item id is usually 'latest'
        Location location = glass.locations().get(notification.getItemId()).execute();

        LOG.info("New location is " + location.getLatitude() + ", " + location.getLongitude());
        MirrorClient.insertTimelineItem(credential, new TimelineItem()
                .setText("Java Quick Start says you are now at " + location.getLatitude() + " by "
                        + location.getLongitude())
                .setNotification(new NotificationConfig().setLevel("DEFAULT")).setLocation(location)
                .setMenuItems(Lists.newArrayList(new MenuItem().setAction("NAVIGATE"))));

        // This is a location notification. Ping the device with a timeline item
        // telling them where they are.
    } else if (notification.getCollection().equals("timeline")) {
        // Get the impacted timeline item
        TimelineItem timelineItem = mirrorClient.timeline().get(notification.getItemId()).execute();
        LOG.info("Notification impacted timeline item with ID: " + timelineItem.getId());

        // If it was a share, and contains a photo, update the photo's caption to
        // acknowledge that we got it.
        if (notification.getUserActions().contains(new UserAction().setType("SHARE"))
                && timelineItem.getAttachments() != null && timelineItem.getAttachments().size() > 0) {
            String finalresponseForCard = null;

            String questionString = timelineItem.getText();
            if (!questionString.isEmpty()) {
                String[] questionStringArray = questionString.split(" ");

                LOG.info(timelineItem.getText() + " is the questions asked by the user");
                LOG.info("A picture was taken");

                if (questionString.toLowerCase().contains("search")
                        || questionString.toLowerCase().contains("tag")
                        || questionString.toLowerCase().contains("train")
                        || questionString.toLowerCase().contains("mark")
                        || questionString.toLowerCase().contains("recognize")
                        || questionString.toLowerCase().contains("what is")) {

                    //Fetching the image from the timeline
                    InputStream inputStream = downloadAttachment(mirrorClient, notification.getItemId(),
                            timelineItem.getAttachments().get(0));

                    //converting the image to Base64
                    Base64 base64Object = new Base64(false);
                    String encodedImageToBase64 = base64Object.encodeToString(IOUtils.toByteArray(inputStream)); //byteArrayForOutputStream.toByteArray()
                    // byteArrayForOutputStream.close();
                    encodedImageToBase64 = java.net.URLEncoder.encode(encodedImageToBase64, "ISO-8859-1");

                    //sending the API request
                    LOG.info("Sending request to API");
                    //For initial protoype we're calling the Alchemy API for detecting the number of Faces using web API call
                    try {
                        String urlParameters = "";
                        String tag = "";

                        if (questionString.toLowerCase().contains("tag")
                                || questionString.toLowerCase().contains("mark")) {

                            tag = extractTagFromQuestion(questionString);
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_add&name_space=recognizeObject&user_id=user1&tag="
                                    + tag + "&base64=" + encodedImageToBase64;

                        } else if (questionString.toLowerCase().contains("train")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_train&name_space=recognizeObject&user_id=user1";
                        } else if (questionString.toLowerCase().contains("search")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_search&name_space=recognizeObject&user_id=user1&base64="
                                    + encodedImageToBase64;
                        } else if (questionString.toLowerCase().contains("recognize")
                                || questionString.toLowerCase().contains("what is")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_recognize&name_space=recognizeObject&user_id=user1&base64="
                                    + encodedImageToBase64;
                        }
                        byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
                        int postDataLength = postData.length;
                        String newrequest = "http://rekognition.com/func/api/";
                        URL url = new URL(newrequest);
                        HttpURLConnection connectionFaceDetection = (HttpURLConnection) url.openConnection();

                        // Increase the timeout for reading the response
                        connectionFaceDetection.setReadTimeout(15000);

                        connectionFaceDetection.setDoOutput(true);
                        connectionFaceDetection.setDoInput(true);
                        connectionFaceDetection.setInstanceFollowRedirects(false);
                        connectionFaceDetection.setRequestMethod("POST");
                        connectionFaceDetection.setRequestProperty("Content-Type",
                                "application/x-www-form-urlencoded");
                        connectionFaceDetection.setRequestProperty("X-Mashape-Key",
                                "pzFbNRvNM4mshgWJvvdw0wpLp5N1p1X3AX9jsnOhjDUkn5Lvrp");
                        connectionFaceDetection.setRequestProperty("charset", "utf-8");
                        connectionFaceDetection.setRequestProperty("Accept", "application/json");
                        connectionFaceDetection.setRequestProperty("Content-Length",
                                Integer.toString(postDataLength));
                        connectionFaceDetection.setUseCaches(false);

                        DataOutputStream outputStreamForFaceDetection = new DataOutputStream(
                                connectionFaceDetection.getOutputStream());
                        outputStreamForFaceDetection.write(postData);

                        BufferedReader inputStreamForFaceDetection = new BufferedReader(
                                new InputStreamReader((connectionFaceDetection.getInputStream())));

                        StringBuilder responseForFaceDetection = new StringBuilder();

                        while ((responseStringForFaceDetection = inputStreamForFaceDetection
                                .readLine()) != null) {
                            responseForFaceDetection.append(responseStringForFaceDetection);
                        }

                        //closing all the connections
                        inputStreamForFaceDetection.close();
                        outputStreamForFaceDetection.close();
                        connectionFaceDetection.disconnect();

                        responseStringForFaceDetection = responseForFaceDetection.toString();
                        LOG.info(responseStringForFaceDetection);

                        JSONObject responseJSONObjectForFaceDetection = new JSONObject(
                                responseStringForFaceDetection);
                        if (questionString.toLowerCase().contains("train") || questionString.contains("tag")
                                || questionString.toLowerCase().contains("mark")) {
                            JSONObject usageKeyFromResponse = responseJSONObjectForFaceDetection
                                    .getJSONObject("usage");
                            finalresponseForCard = usageKeyFromResponse.getString("status");
                            if (!tag.equals(""))
                                finalresponseForCard = "Object is tagged as " + tag;
                        } else {
                            JSONObject sceneUnderstandingObject = responseJSONObjectForFaceDetection
                                    .getJSONObject("scene_understanding");
                            JSONArray matchesArray = sceneUnderstandingObject.getJSONArray("matches");
                            JSONObject firstResultFromArray = matchesArray.getJSONObject(0);

                            double percentSureOfObject;
                            //If an score has value 1, then the value type is Integer else the value type is double
                            if (firstResultFromArray.get("score") instanceof Integer) {
                                percentSureOfObject = (Integer) firstResultFromArray.get("score") * 100;
                            } else
                                percentSureOfObject = (Double) firstResultFromArray.get("score") * 100;

                            finalresponseForCard = "The object is " + firstResultFromArray.getString("tag")
                                    + ". Match score is" + percentSureOfObject;
                        }

                        //section where if it doesn't contain anything about tag or train

                    } catch (Exception e) {
                        LOG.warning(e.getMessage());
                    }

                }

                else
                    finalresponseForCard = "Could not understand your words";
            } else
                finalresponseForCard = "Could not understand your words";

            TimelineItem responseCardForSDKAlchemyAPI = new TimelineItem();

            responseCardForSDKAlchemyAPI.setText(finalresponseForCard);
            responseCardForSDKAlchemyAPI
                    .setMenuItems(Lists.newArrayList(new MenuItem().setAction("READ_ALOUD")));
            responseCardForSDKAlchemyAPI.setSpeakableText(finalresponseForCard);
            responseCardForSDKAlchemyAPI.setSpeakableType("Results are as follows");
            responseCardForSDKAlchemyAPI.setNotification(new NotificationConfig().setLevel("DEFAULT"));
            mirrorClient.timeline().insert(responseCardForSDKAlchemyAPI).execute();
            LOG.info("New card added to the timeline");

        } else if (notification.getUserActions().contains(new UserAction().setType("LAUNCH"))) {
            LOG.info("It was a note taken with the 'take a note' voice command. Processing it.");

            // Grab the spoken text from the timeline card and update the card with
            // an HTML response (deleting the text as well).
            String noteText = timelineItem.getText();
            String utterance = CAT_UTTERANCES[new Random().nextInt(CAT_UTTERANCES.length)];

            timelineItem.setText(null);
            timelineItem.setHtml(makeHtmlForCard(
                    "<p class='text-auto-size'>" + "Oh, did you say " + noteText + "? " + utterance + "</p>"));
            timelineItem.setMenuItems(Lists.newArrayList(new MenuItem().setAction("DELETE")));

            mirrorClient.timeline().update(timelineItem.getId(), timelineItem).execute();
        } else {
            LOG.warning("I don't know what to do with this notification, so I'm ignoring it.");
        }
    }
}

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

@Override
public Status upload(SQLiteDatabase db, long mID) {
    Status s;/*from w  ww  .j  a v a2s. c  o m*/
    if ((s = connect()) != Status.OK) {
        return s;
    }

    TCX tcx = new TCX(db);
    HttpURLConnection conn = null;
    Exception ex = null;
    try {
        StringWriter writer = new StringWriter();
        String id = tcx.export(mID, writer);
        conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        addCookies(conn);
        getFormValues(conn); // execute the GET
        conn.disconnect();

        String viewKey = findName(formValues.keySet(), "VIEWSTATE");
        String eventKey = findName(formValues.keySet(), "EVENTVALIDATION");
        String fileKey = findName(formValues.keySet(), "FileUpload");
        String uploadKey = findName(formValues.keySet(), "UploadButton");

        Part<StringWritable> part1 = new Part<StringWritable>(viewKey,
                new StringWritable(formValues.get(viewKey)));

        Part<StringWritable> part2 = new Part<StringWritable>(eventKey,
                new StringWritable(formValues.get(eventKey)));

        Part<StringWritable> part3 = new Part<StringWritable>(fileKey, new StringWritable(writer.toString()));
        part3.contentType = "application/octet-stream";
        part3.filename = "jonas.tcx";

        Part<StringWritable> part4 = new Part<StringWritable>(uploadKey,
                new StringWritable(formValues.get(uploadKey)));
        Part<?> parts[] = { part1, part2, part3, part4 };

        conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        addCookies(conn);
        postMulti(conn, parts);
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        getCookies(conn);
        String redirect = null;
        if (responseCode == 302) {
            redirect = conn.getHeaderField("Location");
            conn.disconnect();
            conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("GET");
            addCookies(conn);
            responseCode = conn.getResponseCode();
            amsg = conn.getResponseMessage();
            getCookies(conn);
        } else if (responseCode != 200) {
            System.err.println("FunBeatUploader::upload() - got " + responseCode + ", msg: " + amsg);
        }
        getFormValues(conn);
        conn.disconnect();

        viewKey = findName(formValues.keySet(), "VIEWSTATE");
        eventKey = findName(formValues.keySet(), "EVENTVALIDATION");
        String nextKey = findName(formValues.keySet(), "NextButton");
        String hidden = findName(formValues.keySet(), "ChoicesHiddenField");

        FormValues kv = new FormValues();
        kv.put(viewKey, formValues.get(viewKey));
        kv.put(eventKey, formValues.get(eventKey));
        kv.put(nextKey, "Nasta >>");
        kv.put(hidden, "[ \"import///" + id + "///tcx\" ]");

        String surl = BASE_URL + redirect;
        conn = (HttpURLConnection) new URL(surl).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        addCookies(conn);
        {
            OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
            kv.write(wr);
            wr.flush();
            wr.close();
            responseCode = conn.getResponseCode();
            amsg = conn.getResponseMessage();
            getCookies(conn);
            if (responseCode == 302) {
                redirect = conn.getHeaderField("Location");
                conn.disconnect();
                conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setRequestMethod("GET");
                addCookies(conn);
                responseCode = conn.getResponseCode();
                amsg = conn.getResponseMessage();
                getCookies(conn);
            }
            String html = getFormValues(conn);
            boolean ok = html.indexOf("r klar") > 0;
            System.err.println("ok: " + ok);

            conn.disconnect();
            if (ok) {
                return Uploader.Status.OK;
            } else {
                return Uploader.Status.CANCEL;
            }
        }
    } catch (IOException e) {
        ex = e;
    }

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

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

@Override
public Status upload(SQLiteDatabase db, long mID) {
    Status s;/*from   www  .  j  av  a 2 s.c  om*/
    if ((s = connect()) != Status.OK) {
        return s;
    }

    TCX tcx = new TCX(db);
    HttpURLConnection conn = null;
    Exception ex = null;
    try {
        StringWriter writer = new StringWriter();
        String id = tcx.export(mID, writer);
        conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        addCookies(conn);
        getFormValues(conn); // execute the GET
        conn.disconnect();

        String viewKey = SyncHelper.findName(formValues.keySet(), "VIEWSTATE");
        String eventKey = SyncHelper.findName(formValues.keySet(), "EVENTVALIDATION");
        String fileKey = SyncHelper.findName(formValues.keySet(), "FileUpload");
        String uploadKey = SyncHelper.findName(formValues.keySet(), "UploadButton");

        Part<StringWritable> part1 = new Part<StringWritable>(viewKey,
                new StringWritable(formValues.get(viewKey)));

        Part<StringWritable> part2 = new Part<StringWritable>(eventKey,
                new StringWritable(formValues.get(eventKey)));

        Part<StringWritable> part3 = new Part<StringWritable>(fileKey, new StringWritable(writer.toString()));
        part3.setContentType("application/octet-stream");
        part3.setFilename("jonas.tcx");

        Part<StringWritable> part4 = new Part<StringWritable>(uploadKey,
                new StringWritable(formValues.get(uploadKey)));
        Part<?> parts[] = { part1, part2, part3, part4 };

        conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        addCookies(conn);
        SyncHelper.postMulti(conn, parts);
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        getCookies(conn);
        String redirect = null;
        if (responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            redirect = conn.getHeaderField("Location");
            conn.disconnect();
            conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod(RequestMethod.GET.name());
            addCookies(conn);
            responseCode = conn.getResponseCode();
            amsg = conn.getResponseMessage();
            getCookies(conn);
        } else if (responseCode != HttpStatus.SC_OK) {
            Log.e(getName(), "FunBeatSynchronizer::upload() - got " + responseCode + ", msg: " + amsg);
        }
        getFormValues(conn);
        conn.disconnect();

        viewKey = SyncHelper.findName(formValues.keySet(), "VIEWSTATE");
        eventKey = SyncHelper.findName(formValues.keySet(), "EVENTVALIDATION");
        String nextKey = SyncHelper.findName(formValues.keySet(), "NextButton");
        String hidden = SyncHelper.findName(formValues.keySet(), "ChoicesHiddenField");

        FormValues kv = new FormValues();
        kv.put(viewKey, formValues.get(viewKey));
        kv.put(eventKey, formValues.get(eventKey));
        kv.put(nextKey, "Nasta >>");
        kv.put(hidden, "[ \"import///" + id + "///tcx\" ]");

        String surl = BASE_URL + redirect;
        conn = (HttpURLConnection) new URL(surl).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        addCookies(conn);
        {
            OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
            kv.write(wr);
            wr.flush();
            wr.close();
            responseCode = conn.getResponseCode();
            amsg = conn.getResponseMessage();
            getCookies(conn);
            if (responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                redirect = conn.getHeaderField("Location");
                conn.disconnect();
                conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setRequestMethod(RequestMethod.GET.name());
                addCookies(conn);
                responseCode = conn.getResponseCode();
                amsg = conn.getResponseMessage();
                getCookies(conn);
            }
            String html = getFormValues(conn);
            boolean ok = html.indexOf("r klar") > 0;
            Log.e(getName(), "ok: " + ok);

            conn.disconnect();
            if (ok) {
                s = Status.OK;
                s.activityId = mID;
            } else {
                s = Status.CANCEL;
            }
            return s;
        }
    } catch (IOException e) {
        ex = e;
    }

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

From source file:guru.benson.pinch.Pinch.java

/**
 * Gets the list of files included in the ZIP stored on the HTTP server.
 *
 * @return A list of ZIP entries.// w w  w  .jav  a 2  s . co m
 */
public ArrayList<ExtendedZipEntry> parseCentralDirectory() {
    int contentLength = getHttpFileSize();
    if (contentLength <= 0) {
        return null;
    }

    if (!findCentralDirectory(contentLength)) {
        return null;
    }

    HttpURLConnection conn = null;
    InputStream bis = null;

    long start = centralDirectoryOffset;
    long end = start + centralDirectorySize - 1;

    byte[] data = new byte[2048];
    ByteBuffer buf = ByteBuffer.allocate(centralDirectorySize);

    try {
        conn = openConnection();
        conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
        conn.setInstanceFollowRedirects(true);
        conn.connect();

        int responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_PARTIAL) {
            throw new IOException("Unexpected HTTP server response: " + responseCode);
        }

        bis = conn.getInputStream();
        int read, bytes = 0;
        while ((read = bis.read(data)) != -1) {
            buf.put(data, 0, read);
            bytes += read;
        }

        log("Central directory is " + bytes + " bytes");

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        close(bis);
        disconnect(conn);
    }

    return parseHeaders(buf);
}

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

@Override
public Status upload(SQLiteDatabase db, long mID) {
    Status s;/*  w w w . ja va 2  s  .  c  o m*/
    if ((s = connect()) != Status.OK) {
        return s;
    }

    StringWriter writer = new StringWriter();
    TCX tcx = new TCX(db);

    HttpURLConnection conn = null;
    try {
        Pair<String, Sport> res = tcx.exportWithSport(mID, writer);
        Sport sport = res.second;
        String filename = String.format("activity%s%d.tcx", Long.toString(Math.round(1000 * Math.random())),
                mID);

        String url = UPLOAD_URL + "?authenticity_token=" + SyncHelper.URLEncode(authToken) + "&qqfile="
                + filename;
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        conn.addRequestProperty("Host", "www.runtastic.com");
        conn.addRequestProperty("X-Requested-With", "XMLHttpRequest");
        conn.addRequestProperty("X-File-Name", filename);
        conn.addRequestProperty("Content-Type", "application/octet-stream");
        addRequestHeaders(conn);

        OutputStream out = new BufferedOutputStream(conn.getOutputStream());
        out.write(writer.toString().getBytes());
        out.flush();
        out.close();
        InputStream in = new BufferedInputStream(conn.getInputStream());
        JSONObject ret = SyncHelper.parse(in);
        getCookies(conn);
        if (ret == null || !ret.has("success") || !ret.getBoolean("success")) {
            Log.i(getName(), "ret: " + ret);
            throw new JSONException("Unexpected json return");
        }

        String tmp = ret.getString("content");
        final String name = "name='";
        int i1 = tmp.indexOf(name);
        if (i1 < 0) {
            Log.i(getName(), "ret: " + ret);
            throw new JSONException("Unexpected json return");
        }
        i1 += name.length();
        int i2 = tmp.indexOf('\'', i1);
        String import_id = tmp.substring(i1, i2);
        Log.i(getName(), "import_id: " + import_id);
        conn.disconnect();

        if (sport != null && sport != Sport.RUNNING && sport2runtasticMap.containsKey(sport)) {
            conn = (HttpURLConnection) new URL(UPDATE_SPORTS_TYPE).openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod(RequestMethod.POST.name());
            conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.addRequestProperty("X-Requested-With", "XMLHttpRequest");
            addRequestHeaders(conn);

            FormValues fv = new FormValues();
            fv.put("authenticity_token", authToken);
            fv.put("data_import_id", import_id);
            fv.put("sport_type_id", sport2runtasticMap.get(sport).toString());
            fv.put("user_id", userId.toString());
            SyncHelper.postData(conn, fv);
            int responseCode = conn.getResponseCode();
            String amsg = conn.getResponseMessage();
            Log.i(getName(), "code: " + responseCode + ", html: " + getFormValues(conn));
            conn.disconnect();
        }
        logout();
        s = Status.OK;
        s.activityId = mID;
        return s;

    } catch (IOException ex) {
        s = Status.ERROR;
        s.ex = ex;
    } catch (JSONException e) {
        s = Status.ERROR;
        s.ex = e;
    }

    if (s.ex != null)
        Log.e(getName(), "ex: " + s.ex);

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

    s.activityId = mID;
    return s;
}

From source file:org.apache.hadoop.fs.http.client.HttpFSFileSystem.java

private FSDataOutputStream uploadData(String method, Path f, Map<String, String> params, int bufferSize,
        int expectedStatus) throws IOException {
    HttpURLConnection conn = getConnection(method, params, f, true);
    conn.setInstanceFollowRedirects(false);
    boolean exceptionAlreadyHandled = false;
    try {//  w  w w.j  a  v  a 2 s  .  c  o m
        if (conn.getResponseCode() == HTTP_TEMPORARY_REDIRECT) {
            exceptionAlreadyHandled = true;
            String location = conn.getHeaderField("Location");
            if (location != null) {
                conn = getConnection(new URL(location), method);
                conn.setRequestProperty("Content-Type", UPLOAD_CONTENT_TYPE);
                try {
                    OutputStream os = new BufferedOutputStream(conn.getOutputStream(), bufferSize);
                    return new HttpFSDataOutputStream(conn, os, expectedStatus, statistics);
                } catch (IOException ex) {
                    validateResponse(conn, expectedStatus);
                    throw ex;
                }
            } else {
                validateResponse(conn, HTTP_TEMPORARY_REDIRECT);
                throw new IOException("Missing HTTP 'Location' header for [" + conn.getURL() + "]");
            }
        } else {
            throw new IOException(MessageFormat.format("Expected HTTP status was [307], received [{0}]",
                    conn.getResponseCode()));
        }
    } catch (IOException ex) {
        if (exceptionAlreadyHandled) {
            throw ex;
        } else {
            validateResponse(conn, HTTP_TEMPORARY_REDIRECT);
            throw ex;
        }
    }
}

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

String refreshToken(String refresh_token) {
    // android.os.Debug.waitForDebugger();

    Log.d(TAG, "refreshToken= " + refresh_token);

    // check initialization
    if (mOcp == null || isEmpty(mOcp.m_server_url))
        return null;

    // nothing to do
    if (isEmpty(refresh_token))
        return null;

    String postUrl = mOcp.m_server_url + "token";

    // set up connection
    HttpURLConnection huc = getHUC(postUrl);
    huc.setDoOutput(true);// w  ww.  j  a va  2  s  .c  o m
    huc.setInstanceFollowRedirects(false);
    huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // prepare parameters
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
    nameValuePairs.add(new BasicNameValuePair("client_id", mOcp.m_client_id));
    nameValuePairs.add(new BasicNameValuePair("client_secret", mOcp.m_client_secret));

    nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token"));
    nameValuePairs.add(new BasicNameValuePair("refresh_token", refresh_token));
    if (!isEmpty(mOcp.m_scope))
        nameValuePairs.add(new BasicNameValuePair("scope", mOcp.m_scope));

    try {
        // write parameters to http connection
        OutputStream os = huc.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        // get URL encoded string from list of key value pairs
        String postParam = getQuery(nameValuePairs);
        Logd("refreshToken", "url: " + postUrl);
        Logd("refreshToken", "POST: " + postParam);
        writer.write(postParam);
        writer.flush();
        writer.close();
        os.close();

        // try to connect
        huc.connect();
        // connexion status
        int responseCode = huc.getResponseCode();
        Logd(TAG, "refreshToken response: " + responseCode);

        // if 200 - OK, read the json string
        if (responseCode == 200) {
            sysout("refresh_token - code " + responseCode);
            InputStream is = huc.getInputStream();
            String result = convertStreamToString(is);
            is.close();
            huc.disconnect();

            Logd("refreshToken", "result: " + result);
            sysout("refresh_token - content: " + result);

            return result;
        }
        huc.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}