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.github.thesmartenergy.sparql.generate.api.Take.java

@GET
public Response doGet(@Context Request r, @Context HttpServletRequest request,
        @DefaultValue("") @QueryParam("accept") String accept) throws IOException {

    String message = IOUtils.toString(request.getInputStream());
    // if content encoding is not text-based, then use base64 encoding
    // use con.getContentEncoding() for this
    String dturi = "http://www.w3.org/2001/XMLSchema#string";
    String ct = request.getContentType();
    if (ct != null) {
        dturi = "urn:iana:mime:" + ct;
    }//from   www  .java 2s  .  c  o m

    String queryuri = request.getHeader("SPARGL-Query");
    String var = request.getHeader("SPARGL-Variable");
    HttpURLConnection con;
    String query = null;
    try {
        URL obj = new URL(queryuri);
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", "application/sparql-generate");
        con.setInstanceFollowRedirects(true);
        System.out.println("GET to " + queryuri + " returned " + con.getResponseCode());
        InputStream in = con.getInputStream();
        query = IOUtils.toString(in);
    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity("Error while trying to access query at URI <" + queryuri + ">: " + e.getMessage())
                .build();
    }
    System.out.println("got query " + query);

    // parse the SPARQL-Generate query and create plan
    PlanFactory factory = new PlanFactory();

    Syntax syntax = SPARQLGenerate.SYNTAX;
    SPARQLGenerateQuery q = (SPARQLGenerateQuery) QueryFactory.create(query, syntax);
    if (q.getBaseURI() == null) {
        q.setBaseURI("http://example.org/");
    }
    RootPlan plan = factory.create(q);

    // create the initial model
    Model model = ModelFactory.createDefaultModel();

    QuerySolutionMap initialBinding = new QuerySolutionMap();
    TypeMapper typeMapper = TypeMapper.getInstance();
    RDFDatatype dt = typeMapper.getSafeTypeByName(dturi);
    Node arqLiteral = NodeFactory.createLiteral(message, dt);
    RDFNode jenaLiteral = model.asRDFNode(arqLiteral);
    initialBinding.add(var, jenaLiteral);

    // execute the plan
    plan.exec(initialBinding, model);

    System.out.println(accept);
    if (!accept.equals("text/turtle") && !accept.equals("application/rdf+xml")) {
        List<Variant> vs = Variant
                .mediaTypes(new MediaType("application", "rdf+xml"), new MediaType("text", "turtle")).build();
        Variant v = r.selectVariant(vs);
        accept = v.getMediaType().toString();
    }

    System.out.println(accept);
    StringWriter sw = new StringWriter();
    Response.ResponseBuilder res;
    if (accept.equals("application/rdf+xml")) {
        model.write(sw, "RDF/XML", "http://example.org/");
        res = Response.ok(sw.toString(), "application/rdf+xml");
        res.header("Content-Disposition", "filename= message.rdf;");
        return res.build();
    } else {
        model.write(sw, "TTL", "http://example.org/");
        res = Response.ok(sw.toString(), "text/turtle");
        res.header("Content-Disposition", "filename= message.ttl;");
        return res.build();
    }
}

From source file:com.amastigote.xdu.query.module.EduSystem.java

@Override
public boolean checkIsLogin(String username) throws IOException {
    URL url = new URL(SYS_HOST + SYS_SUFFIX);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setInstanceFollowRedirects(false);
    httpURLConnection.setRequestProperty("Cookie", "JSESSIONID=" + SYS_JSESSIONID);
    httpURLConnection.connect();/*from   w w w .  ja va  2s. com*/

    Document document = Jsoup.parse(httpURLConnection.getInputStream(), "gb2312",
            httpURLConnection.getURL().toString());
    if (document.select("title").size() == 0) {
        return false;
    } else if (document.select("title").get(0).text().equals("?")) {
        ID = username;
        return true;
    }
    return false;
}

From source file:org.openbravo.test.datasource.TestAllowUnpagedDatasourcePreference.java

private HttpURLConnection createConnection(String wsPart, String method) throws Exception {
    Authenticator.setDefault(new Authenticator() {
        @Override//from   w  w  w .j a v  a 2 s  .  c o  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(LOGIN, PWD.toCharArray());
        }
    });
    final URL url = new URL(getOpenbravoURL() + wsPart);
    final HttpURLConnection hc = (HttpURLConnection) url.openConnection();
    hc.setRequestMethod(method);
    hc.setAllowUserInteraction(false);
    hc.setDefaultUseCaches(false);
    hc.setDoOutput(true);
    hc.setDoInput(true);
    hc.setInstanceFollowRedirects(true);
    hc.setUseCaches(false);
    hc.setRequestProperty("Content-Type", "text/xml");
    return hc;
}

From source file:org.lnicholls.galleon.util.IMDB.java

public static void getMovie2(Movie movie) {

    String imdb = movie.getIMDB();

    if (imdb == null || imdb.length() == 0)

    {/*w w w . j  a va  2 s  . com*/

        imdb = getIMDBID(movie.getTitle());

    }

    if (imdb != null) {

        movie.setIMDB(imdb);

        StringBuffer buffer = new StringBuffer();

        byte[] buf = new byte[1024];

        int amount = 0;

        try {

            URL url = new URL("http://nicholls.us/imdb/imdbxml.php?mid=" + imdb);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestProperty("User-Agent", "Galleon " + Tools.getVersion());

            conn.setInstanceFollowRedirects(true);

            InputStream input = conn.getInputStream();

            while ((amount = input.read(buf)) > 0) {

                buffer.append(new String(buf, 0, amount));

            }

            input.close();

            conn.disconnect();

            SAXReader saxReader = new SAXReader();

            StringReader stringReader = new StringReader(buffer.toString().trim());

            Document document = saxReader.read(stringReader);

            //Document document = saxReader.read(new File("d:/galleon/imdb.xml"));

            Element root = document.getRootElement();

            movie.setTitle(clean(Tools.getAttribute(root, "title")));

            try

            {

                movie.setDate(Integer.parseInt(clean(Tools.getAttribute(root, "year"))));

            }

            catch (Exception ex) {
            }

            movie.setThumbUrl(clean(Tools.getAttribute(root, "photoUrl")));

            try

            {

                movie.setDuration(Integer.parseInt(clean(Tools.getAttribute(root, "runtime"))));

            }

            catch (Exception ex) {
            }

            movie.setRating((int) Float.parseFloat(clean(Tools.getAttribute(root, "rating"))));

            movie.setRated(clean(Tools.getAttribute(root, "rated")));

            movie.setGenre(clean(Tools.getAttribute(root, "genres")));

            movie.setTagline(clean(Tools.getAttribute(root, "tagline")));

            movie.setDirector(clean(Tools.getAttribute(root, "director")));

            movie.setCredits(clean(Tools.getAttribute(root, "writer")));

            movie.setProducer(clean(Tools.getAttribute(root, "producer")));

            movie.setActors(clean(Tools.getAttribute(root, "cast")));

            movie.setPlotOutline(clean(Tools.getAttribute(root, "outline")));

            movie.setPlot(clean(Tools.getAttribute(root, "plot")));

        } catch (Exception ex) {

            Tools.logException(IMDB.class, ex, "Could not get IMDB data: " + movie.getTitle());

        }

    }

}

From source file:zoho.ZohoService.java

/**
 * Add a new task to a project/* w ww . j av  a  2  s  .co m*/
 * @param token User token
 * @param portal Portal id
 * @param project project id
 * @param taskName Task name
 * @param taskStartDate Start date
 * @param taskEndDate End date
 * @param taskPriority Priority
 * @param taskDesc Description
 * @return response code or -1 if fail
 */
public int addTask(String token, String portal, String project, String taskName, String taskStartDate,
        String taskEndDate, String taskPriority, String taskDesc) {
    int res = -1;
    try {
        String urlParam = "name=" + taskName;
        if (!taskStartDate.isEmpty()) {
            urlParam += "&start_date=" + taskStartDate;
        }
        if (!taskEndDate.isEmpty()) {
            urlParam += "&end_date=" + taskEndDate;
        }
        if (!taskPriority.isEmpty()) {
            urlParam += "&priority=" + taskPriority;
        }
        if (!taskDesc.isEmpty()) {
            urlParam += "&description=" + taskDesc;
        }
        urlParam += "&authtoken=" + token;
        String url = this.baseUrl + "/portal/" + portal + "/projects/" + project;
        url += "/tasks/";
        byte[] postData = urlParam.getBytes(StandardCharsets.UTF_8);
        int postDataLength = postData.length;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Mozilla/40.0");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("charset", "utf-8");
        con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        con.setUseCaches(false);

        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.write(postData);
        }
        int responseCode = con.getResponseCode();
        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();
        res = responseCode;
    } catch (MalformedURLException ex) {
        Logger.getLogger(ZohoService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ZohoService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        System.out.println("Some error occured... Please come back later.. :(");
    }
    return res;
}

From source file:org.atricore.idbus.capabilities.josso.test.JOSSO11WebSSORouteTest.java

public void testJOSSO11AuthNRequestToSAMLR2() throws Exception {
    String location = null;// w  ww. j  a v  a 2 s  .  c o  m
    URL spUrl = new URL("http://localhost:8181/JOSSO11/BIND/CH1?cmd=login");
    HttpURLConnection urlConn = (HttpURLConnection) spUrl.openConnection();
    urlConn.setInstanceFollowRedirects(false);
    urlConn.connect();

    String headerName = null;
    String jossoSession = null;
    for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) {
        if (headerName.equals("Location")) {
            location = urlConn.getHeaderField(i);
        }
    }

    assert location != null;

}

From source file:org.atricore.idbus.capabilities.josso.test.JOSSO11WebSSORouteTest.java

public void testSAMLR2AuthnToJOSSO11() throws Exception {
    String location = null;/*from  w  w  w .  j  a v a  2  s  . c o  m*/
    URL spUrl = new URL("http://localhost:8181/JOSSO11/BIND/CH2?SAMLRequest=" + BASE64_SAMLR2_AUTHNREQUEST);
    HttpURLConnection urlConn = (HttpURLConnection) spUrl.openConnection();
    urlConn.setInstanceFollowRedirects(false);
    urlConn.connect();

    String headerName = null;
    String jossoSession = null;
    for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) {
        if (headerName.equals("Location")) {
            location = urlConn.getHeaderField(i);
        }
    }

    assert location != null;

}

From source file:URLTree.FindOptimalPath.java

public void varifiedSequece(List<FilterURL> varifiedList, PrintWriter writer) {
    for (int i = 0; i < varifiedList.size() - 1; i++) {
        if (varifiedList.get(i).getReversedURL().contains(varifiedList.get(i + 1).getReversedURL())) {

        } else {/*  ww  w  . j av  a  2s . c  om*/
            String nodesName[] = varifiedList.get(i).getReversedURL().split("-");
            if (nodesName.length == 2) {
                try {
                    String url2Domain = "http://" + nodesName[1] + "." + nodesName[0];
                    URL url = new URL(url2Domain);
                    // open connection
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url
                            .openConnection(Proxy.NO_PROXY);

                    // stop following browser redirect
                    httpURLConnection.setInstanceFollowRedirects(false);
                    httpURLConnection.setConnectTimeout(15000);
                    httpURLConnection.setReadTimeout(15000);
                    // extract location header containing the actual destination URL
                    String expandedURL = httpURLConnection.getHeaderField("Location");
                    httpURLConnection.disconnect();
                    if (expandedURL != null) {
                        System.out.println("Correct: " + expandedURL);
                        writer.println(
                                varifiedList.get(i).getReversedURL() + "," + varifiedList.get(i).getCount());
                    }

                } catch (Exception e) {
                    System.out.println("Incorrect: " + e);
                }
            } else {
                writer.println(varifiedList.get(i).getReversedURL() + "," + varifiedList.get(i).getCount());
            }

        }

    }
}

From source file:com.example.gaefirebaseeventproxy.FirebaseEventProxy.java

public void start() {
    DatabaseReference firebase = FirebaseDatabase.getInstance().getReference();

    // Subscribe to value events. Depending on use case, you may want to subscribe to child events
    // through childEventListener.
    firebase.addValueEventListener(new ValueEventListener() {
        @Override/*from  www . j a v  a2 s  .  c o m*/
        public void onDataChange(DataSnapshot snapshot) {
            if (snapshot.exists()) {
                try {
                    // Convert value to JSON using Jackson
                    String json = new ObjectMapper().writeValueAsString(snapshot.getValue(false));

                    // Replace the URL with the url of your own listener app.
                    URL dest = new URL("http://gae-firebase-listener-python.appspot.com/log");
                    HttpURLConnection connection = (HttpURLConnection) dest.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setDoOutput(true);

                    // Rely on X-Appengine-Inbound-Appid to authenticate. Turning off redirects is
                    // required to enable.
                    connection.setInstanceFollowRedirects(false);

                    // Fill out header if in dev environment
                    if (SystemProperty.environment.value() != SystemProperty.Environment.Value.Production) {
                        connection.setRequestProperty("X-Appengine-Inbound-Appid", "dev-instance");
                    }

                    // Put Firebase data into http request
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("&fbSnapshot=");
                    stringBuilder.append(URLEncoder.encode(json, "UTF-8"));
                    connection.getOutputStream().write(stringBuilder.toString().getBytes());
                    if (connection.getResponseCode() != 200) {
                        log.severe("Forwarding failed");
                    } else {
                        log.info("Sent: " + json);
                    }
                } catch (JsonProcessingException e) {
                    log.severe("Unable to convert Firebase response to JSON: " + e.getMessage());
                } catch (IOException e) {
                    log.severe("Error in connecting to app engine: " + e.getMessage());
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError error) {
            log.severe("Firebase connection cancelled: " + error.getMessage());
        }
    });
}

From source file:org.cloudfoundry.identity.app.integration.ServerRunning.java

public RestOperations createRestTemplate() {
    RestTemplate client = new RestTemplate(new SimpleClientHttpRequestFactory() {
        @Override//from  www.  ja  va  2  s .c  om
        protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
            super.prepareConnection(connection, httpMethod);
            connection.setInstanceFollowRedirects(false);
        }
    });
    client.setErrorHandler(new ResponseErrorHandler() {
        // Pass errors through in response entity for status code analysis
        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            return false;
        }

        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
        }
    });
    return client;
}