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:de.nava.informa.utils.FeedManagerEntry.java

/**
 * Loads the channel and sets up the time to expire
 *
 * @param uri The location for the rss file
 * @return The Channel// w w w. j  a v  a2s.  c  o  m
 * @throws FeedManagerException If the feed specified by <code>uri</code> is invalid
 */
private FeedIF retrieveFeed(String uri) throws FeedManagerException {
    try {
        URL urlToRetrieve = new URL(uri);

        URLConnection conn = null;
        try {
            conn = urlToRetrieve.openConnection();

            if (conn instanceof HttpURLConnection) {

                HttpURLConnection httpConn = (HttpURLConnection) conn;

                httpConn.setInstanceFollowRedirects(true); // not needed, default ?

                //    Hack for User-Agent : problem for
                // http://www.diveintomark.org/xml/rss.xml
                HttpHeaderUtils.setUserAgent(httpConn, "Informa Java API");

                logger.debug("retr feed at url " + uri + ": ETag" + HttpHeaderUtils.getETagValue(httpConn)
                        + " if-modified :" + HttpHeaderUtils.getLastModified(httpConn));

                // get initial values for cond. GET in updateChannel
                this.httpHeaders.setETag(HttpHeaderUtils.getETagValue(httpConn));
                this.httpHeaders.setIfModifiedSince(HttpHeaderUtils.getLastModified(httpConn));
            }
        } catch (java.lang.ClassCastException e) {
            logger.warn("problem cast to HttpURLConnection " + uri, e);
            throw new FeedManagerException(e);
        } catch (NullPointerException e) {
            logger.error("problem NPE " + uri + " conn=" + conn, e);
            throw new FeedManagerException(e);
        }

        ChannelIF channel = FeedParser.parse(getChannelBuilder(), conn.getInputStream());
        this.timeToExpire = getTimeToExpire(channel);
        this.feed = new Feed(channel);

        Date currDate = new Date();
        this.feed.setLastUpdated(currDate);
        this.feed.setDateFound(currDate);
        this.feed.setLocation(urlToRetrieve);
        logger.info("feed retrieved " + uri);

    } catch (IOException e) {
        logger.error("IOException " + feedUri + " e=" + e);
        e.printStackTrace();
        throw new FeedManagerException(e);
    } catch (ParseException e) {
        e.printStackTrace();
        throw new FeedManagerException(e);
    }

    return this.feed;
}

From source file:org.neomatrix369.apiworld.APIReader.java

private void preparePostUrl(HttpURLConnection urlConnection) throws ProtocolException {
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);/*from   w  ww .  j  a  va  2 s .co m*/
    urlConnection.setDoInput(true);
    urlConnection.setInstanceFollowRedirects(false);
    urlConnection.setUseCaches(false);

    Map<String, String> requestProperties = new HashMap<String, String>();
    requestProperties.put("Content-Type", "application/x-www-form-urlencoded");
    requestProperties.put("charset", "utf-8");
    requestProperties.putAll(headers);
    setRequestProperties(urlConnection, requestProperties);
}

From source file:io.undertow.servlet.test.streams.ServletInputStreamTestCase.java

private void runTestViaJavaImpl(final String message, String url) throws IOException {
    HttpURLConnection urlcon = null;
    try {/*from ww w  .  ja  va  2s. c  o  m*/
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/" + url;
        urlcon = (HttpURLConnection) new URL(uri).openConnection();
        urlcon.setInstanceFollowRedirects(true);
        urlcon.setRequestProperty("Connection", "close");
        urlcon.setRequestMethod("POST");
        urlcon.setDoInput(true);
        urlcon.setDoOutput(true);
        OutputStream os = urlcon.getOutputStream();
        os.write(message.getBytes());
        os.close();
        Assert.assertEquals(StatusCodes.OK, urlcon.getResponseCode());
        InputStream is = urlcon.getInputStream();

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        byte[] buf = new byte[256];
        int len;
        while ((len = is.read(buf)) > 0) {
            bytes.write(buf, 0, len);
        }
        is.close();
        final String response = new String(bytes.toByteArray(), 0, bytes.size());
        if (!message.equals(response)) {
            System.out.println(String.format("response=%s", Hex.encodeHexString(response.getBytes())));
        }
        Assert.assertEquals(message, response);
    } finally {
        if (urlcon != null) {
            urlcon.disconnect();
        }
    }
}

From source file:org.jenkinsci.test.acceptance.update_center.MockUpdateCenter.java

public void ensureRunning() {
    if (original != null) {
        return;/*from   w ww.j  a v a2 s. com*/
    }
    // TODO this will likely not work on arbitrary controllers, so perhaps limit to the default WinstoneController
    Jenkins jenkins = injector.getInstance(Jenkins.class);
    List<String> sites = new UpdateCenter(jenkins).getJson("tree=sites[url]").findValuesAsText("url");
    if (sites.size() != 1) {
        // TODO ideally it would rather delegate to all of them, but that implies deprecating CachedUpdateCenterMetadataLoader.url and using whatever site(s) Jenkins itself specifies
        LOGGER.log(Level.WARNING, "found an unexpected number of update sites: {0}", sites);
        return;
    }
    UpdateCenterMetadata ucm;
    try {
        ucm = ucmd.get(jenkins);
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot load data for mock update center", x);
        return;
    }
    JSONObject all;
    try {
        all = new JSONObject(ucm.originalJSON);
        all.remove("signature");
        JSONObject plugins = all.getJSONObject("plugins");
        LOGGER.info(() -> "editing JSON with " + plugins.length() + " plugins to reflect " + ucm.plugins.size()
                + " possible overrides");
        for (PluginMetadata meta : ucm.plugins.values()) {
            String name = meta.getName();
            String version = meta.getVersion();
            JSONObject plugin = plugins.optJSONObject(name);
            if (plugin == null) {
                LOGGER.log(Level.INFO, "adding plugin {0}", name);
                plugin = new JSONObject().accumulate("name", name);
                plugins.put(name, plugin);
            }
            plugin.put("url", name + ".hpi");
            updating(plugin, "version", version);
            updating(plugin, "gav", meta.gav);
            updating(plugin, "requiredCore", meta.requiredCore().toString());
            updating(plugin, "dependencies", new JSONArray(meta.getDependencies().stream().map(d -> {
                try {
                    return new JSONObject().accumulate("name", d.name).accumulate("version", d.version)
                            .accumulate("optional", d.optional);
                } catch (JSONException x) {
                    throw new AssertionError(x);
                }
            }).collect(Collectors.toList())));
            plugin.remove("sha1");
        }
    } catch (JSONException x) {
        LOGGER.log(Level.WARNING, "cannot prepare mock update center", x);
        return;
    }
    HttpProcessor proc = HttpProcessorBuilder.create().add(new ResponseServer("MockUpdateCenter"))
            .add(new ResponseContent()).add(new RequestConnControl()).build();
    UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
    String json = "updateCenter.post(\n" + all + "\n);";
    handlerMapper.register("/update-center.json",
            (HttpRequest request, HttpResponse response, HttpContext context) -> {
                response.setStatusCode(HttpStatus.SC_OK);
                response.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
            });
    handlerMapper.register("*.hpi", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String plugin = request.getRequestLine().getUri().replaceFirst("^/(.+)[.]hpi$", "$1");
        PluginMetadata meta = ucm.plugins.get(plugin);
        if (meta == null) {
            LOGGER.log(Level.WARNING, "no such plugin {0}", plugin);
            response.setStatusCode(HttpStatus.SC_NOT_FOUND);
            return;
        }
        File local = meta.resolve(injector, meta.getVersion());
        LOGGER.log(Level.INFO, "serving {0}", local);
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new FileEntity(local));
    });
    handlerMapper.register("*", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String location = original.replace("/update-center.json", request.getRequestLine().getUri());
        LOGGER.log(Level.INFO, "redirect to {0}", location);
        /* TODO for some reason DownloadService.loadJSONHTML does not seem to process the redirect, despite calling setInstanceFollowRedirects(true):
        response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", location);
         */
        HttpURLConnection uc = (HttpURLConnection) new URL(location).openConnection();
        uc.setInstanceFollowRedirects(true);
        // TODO consider caching these downloads locally like CachedUpdateCenterMetadataLoader does for the main update-center.json
        byte[] data = IOUtils.toByteArray(uc);
        String contentType = uc.getContentType();
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new ByteArrayEntity(data, ContentType.create(contentType)));

    });
    server = ServerBootstrap.bootstrap().
    // could setLocalAddress if using a JenkinsController that requires it
            setHttpProcessor(proc).setHandlerMapper(handlerMapper).setExceptionLogger(serverExceptionHandler())
            .create();

    try {
        server.start();
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot start mock update center", x);
        return;

    }
    original = sites.get(0);
    // TODO figure out how to deal with Docker-based controllers which would need to have an IP address for the host
    String override = "http://" + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort()
            + "/update-center.json";
    LOGGER.log(Level.INFO, "replacing update site {0} with {1}", new Object[] { original, override });
    jenkins.runScript(
            "DownloadService.signatureCheck = false; Jenkins.instance.updateCenter.sites.replaceBy([new UpdateSite(UpdateCenter.ID_DEFAULT, '%s')])",
            override);
}

From source file:com.jwrapper.maven.java.JavaDownloadMojo.java

protected HttpURLConnection connection(final String locationURL) throws Exception {

    final URL url = new URL(locationURL);

    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setUseCaches(false);/* ww  w. ja  v  a 2  s .c  o m*/
    connection.setConnectTimeout(10 * 1000);
    connection.setInstanceFollowRedirects(true);

    for (final Map.Entry<String, String> entry : headerMap.entrySet()) {
        connection.setRequestProperty(entry.getKey(), entry.getValue());
    }

    connection.connect();

    return connection;

}

From source file:com.github.thesmartenergy.sparql.generate.api.Transform.java

@GET
public Response doGet(@Context Request r, @Context HttpServletRequest request,
        @DefaultValue("") @QueryParam("message") String message,
        @DefaultValue("") @QueryParam("query") String query,
        @DefaultValue("http://localhost:8080/sparql-generate/query/example1.rqg") @QueryParam("queryuri") String queryuri,
        @DefaultValue("message") @QueryParam("var") String var,
        @DefaultValue("") @QueryParam("accept") String accept) throws IOException {

    //        try {
    HttpSession session = request.getSession();
    List<UniqueLocator> locators = (List<UniqueLocator>) session.getAttribute("locators");
    if (null == locators) {
        locators = new ArrayList<>();
        session.setAttribute("locators", locators);
    }//from  w ww .j av a2 s. co  m

    FileManager fileManager = new FileManager();
    for (Locator loc : locators) {
        fileManager.addLocator(loc);
    }

    System.out.println(queryuri);

    if ("".equals(query)) {
        URL obj = new URL(queryuri);
        HttpURLConnection 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);
    }

    System.out.println("got " + query);

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

    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();

    String uri = "http://www.w3.org/2001/XMLSchema#string";
    QuerySolutionMap initialBinding = new QuerySolutionMap();
    TypeMapper typeMapper = TypeMapper.getInstance();
    RDFDatatype dt = typeMapper.getSafeTypeByName(uri);
    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();
    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();
    }
    //        } catch (Exception e) {
    //            StringWriter sw = new StringWriter();
    //            PrintWriter pw = new PrintWriter(sw);
    //            e.printStackTrace(pw);
    //            return Response.serverError().entity(sw.toString()).build();
    //        }
}

From source file:com.formkiq.core.equifax.service.EquifaxServiceImpl.java

/**
 * Sends request to Equifax.//from  w w w  . ja  v a2 s .  co m
 * @param server {@link String}
 * @param send {@link String}
 * @return {@link String}
 * @throws IOException IOException
 */
public String sendToEquifax(final String server, final String send) throws IOException {

    String params = "InputSegments=" + URLEncoder.encode(send, "UTF-8") + "&cmdSubmit=Submit";

    byte[] postData = params.getBytes(StandardCharsets.UTF_8);
    int postDataLength = postData.length;

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

    conn.setRequestProperty("charset", "utf-8");
    conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
    conn.setUseCaches(false);

    Reader in = null;
    DataOutputStream wr = null;

    try {
        wr = new DataOutputStream(conn.getOutputStream());
        wr.write(postData);

        StringBuilder sb = new StringBuilder();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c = in.read(); c != -1; c = in.read()) {
            sb.append((char) c);
        }

        String receive = sb.toString();

        return receive;

    } finally {

        if (in != null) {
            in.close();
        }

        if (wr != null) {
            wr.close();
        }
    }
}

From source file:sintef.android.gravity.AlarmFragment.java

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if (getView() == null)
        return;/*w w  w.j  a  v  a2  s  . c  om*/

    ButterKnife.inject(this, getView());

    mAlarmView.setOnStopListener(new AlarmView.OnStopListener() {
        @Override
        public void onStop() {
            if (sVibrator != null)
                sVibrator.cancel();
            EventBus.getDefault().post(EventTypes.ALARM_STOPPED);
        }
    });
    mAlarmView.setOnAlarmListener(new AlarmView.OnAlarmListener() {
        @Override
        public void onAlarm() {

            EventBus.getDefault().post(EventTypes.STOP_ALARM);
            Log.w("Alarm", "notifying EMHT");
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    try {
                        String data = "";
                        data += "type=fall&";
                        data += "callee.phoneNumber=" + getResources().getString(R.string.callee_phone_number)
                                + "&";
                        data += "callee.name=" + getResources().getString(R.string.callee_name) + "&";
                        data += "callee.address=" + getResources().getString(R.string.callee_address);
                        Log.w("Alarm", "postdata is: " + data);
                        URL url = new URL(getResources().getString(R.string.server_address) + "/alarm");
                        Log.w("Alarm", "emht server url is: " + url.toString());
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setInstanceFollowRedirects(false);
                        connection.setRequestMethod("POST");
                        BufferedWriter bw = null;
                        try {
                            bw = new BufferedWriter(
                                    new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
                            bw.write(data);
                            bw.flush();
                        } finally {
                            if (bw != null)
                                bw.close();
                        }
                        Log.w("Alarm", "connection response code is: " + connection.getResponseCode());
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    return null;
                }
            }.execute();

            Log.w("Alarm", "calling nextofkin");
            sManager.listen(sPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
            sCallFromApp = true;

            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(
                    Uri.parse("tel:" + PreferencesHelper.getString(Constants.PREFS_NEXT_OF_KIN_TELEPHONE)));
            getActivity().startActivity(intent);
        }
    });

    EventBus.getDefault().register(this);

    boolean start_alarm = getArguments().getBoolean(AlarmService.ALARM_STARTED);

    if (start_alarm)
        mAlarmView.startAlarm();
}

From source file:github.srlee309.lessWrongBookCreator.scraper.PostSectionExtractor.java

/**
 * @param src of image to download and save
 * @param folder to which to save the image
 * @param fileName to use for the saved image
 *//*from  w  ww  .ja  v  a  2  s . co m*/
protected final void saveImage(String src, String folder, String fileName) {
    if (fileName.contains("?")) {
        fileName = fileName.substring(0, fileName.lastIndexOf("?"));
    }

    fileName = fileName.replaceAll("[^a-zA-Z0-9.-]", "_"); // replace non valid file fileName characters
    File outputFile = new File(folder + "\\" + fileName);
    try {
        URL url = new URL(src);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0");
        connection.setRequestMethod("HEAD");
        connection.setInstanceFollowRedirects(false);
        int rspCode = connection.getResponseCode();
        if (rspCode == 301) { // redirected, so get new url
            String newUrl = connection.getHeaderField("Location");
            url = new URL(newUrl);
        }
        connection.disconnect();
        FileUtils.copyURLToFile(url, outputFile);
    } catch (MalformedURLException e) {
        logger.error("Malformed url exception for image src:  " + src, e);
    } catch (IOException e) {
        logger.error("IO exception for saving image src locally:  " + src, e);
    }
}

From source file:org.belio.service.gateway.Gateway.java

private synchronized void doPostJson(JSONObject obj) {
    try {//from   w  w  w  .  ja v  a2  s  .  co m
        // String urlParameters = "param1=a&param2=b&param3=c";
        String request = "http://api.infobip.com/api/v3/sendsms/json";
        URL url = new URL(request);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("charset", "utf-8");
        // connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setUseCaches(false);

        OutputStream wr = connection.getOutputStream();
        //  wr.writeBytes(urlParameters);
        wr.write(obj.toString().getBytes());
        wr.flush();

        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String line;
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
        wr.close();
        rd.close();

        //s wr.close();
        connection.disconnect();
    } catch (MalformedURLException ex) {
        Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ProtocolException ex) {
        Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
    }
}