Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net URLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

public static ResultTiempo calcularTiempo(Context context, int parada, int linea) {
    ResultTiempo result = new ResultTiempo();
    if (!isConnectionEnabled(context)) {
        Log.d("AlmeriBus", "No hay conexin");
        result.setTiempo(ERROR_IO);//from w  w  w  .  j ava  2  s  .  c  om
    }
    try {
        loadCookie();
        URL url = new URL(QUERY_ADDRESS_TIEMPO_PARADA + linea + "/" + parada + "/" + "3B5579C8FFD6");
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(15000);
        connection.setRequestProperty("REFERER", "http://m.surbus.com/tiempo-espera/");
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + cookie);
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        Log.d("Almeribus", strBuilder.toString());
        JSONObject json = new JSONObject(strBuilder.toString());
        boolean isSuccessful = json.getBoolean("success");
        int type = json.getInt("waitTimeType");
        if (isSuccessful && type > 0) {
            int time = json.getInt("waitTime");
            if (time == Integer.MAX_VALUE) {
                time = NO_DATOS;
            }
            if (time <= 0) {
                time = 0;
            }
            result.setTiempo(time);
            result.setTiempoTexto(json.getString("waitTimeString"));
        } else {
            result.setTiempo(NO_DATOS);
        }
    } catch (Exception e) {
        Log.d("Almeribus", e.toString());
        result.setTiempo(ERROR_IO);
        return result;
    }
    return result;
}

From source file:org.spoutcraft.launcher.util.Utils.java

public static String executePost(String targetURL, String urlParameters, JProgressBar progress)
        throws PermissionDeniedException {
    URLConnection connection = null;
    try {//from w w w .j  ava 2  s. c  o m
        URL url = new URL(targetURL);
        connection = url.openConnection();
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.setConnectTimeout(10000);

        connection.connect();

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

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

        StringBuilder response = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();

        return response.toString();
    } catch (SocketException e) {
        if (e.getMessage().equalsIgnoreCase("Permission denied: connect")) {
            throw new PermissionDeniedException("Permission to login was denied");
        }
    } catch (Exception e) {
        String message = "Login failed...";
        progress.setString(message);
    }
    return null;
}

From source file:BihuHttpUtil.java

/**
 * ?URL??GET// w  w w .j a  v a2 s  .  co m
 *
 * @param url
 *            ??URL
 * @param param
 *            ?? name1=value1&name2=value2 ?
 * @return URL ??
 */
public static String sendGet(String url, String param) {
    String result = "";
    BufferedReader in = null;
    try {
        String urlNameString = url + "?" + param;
        URL realUrl = new URL(urlNameString);
        // URL
        URLConnection connection = realUrl.openConnection();
        // 
        connection.setRequestProperty("Host", "quote.zhonghe-bj.com:8085");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
        // 
        connection.connect();
        //  BufferedReader???URL?
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("??GET?" + e);
        e.printStackTrace();
    }
    // finally???
    finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
    return result;
}

From source file:BihuHttpUtil.java

/**
 * ? URL ??POST//from  w ww .  ja va 2s.  c o  m
 *
 * @param url
 *            ?? URL
 * @param param
 *            ?? name1=value1&name2=value2 ?
 * @return ??
 */
public static String sendPost(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        // URL
        URLConnection conn = realUrl.openConnection();
        // 
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // ??POST
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // ?URLConnection?
        out = new PrintWriter(conn.getOutputStream());
        // ???
        out.print(param);
        // flush?
        out.flush();
        // BufferedReader???URL?
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("?? POST ?" + e);
        e.printStackTrace();
    }
    // finally?????
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

From source file:ch.njol.skript.Updater.java

/**
 * Gets the changelogs and release dates of the newest versions
 * /*from w ww . j ava2  s  .  c  o  m*/
 * @param sender
 */
final static void getChangelogs(final CommandSender sender) {
    InputStream in = null;
    InputStreamReader r = null;
    try {
        final URLConnection conn = new URL(RSSURL).openConnection();
        conn.setRequestProperty("User-Agent", "Skript/v" + Skript.getVersion() + " (by Njol)"); // Bukkit returns a 403 (forbidden) if no user agent is set
        in = conn.getInputStream();
        r = new InputStreamReader(in, conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding());
        final XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(r);

        infos.clear();
        VersionInfo current = null;

        outer: while (reader.hasNext()) {
            XMLEvent e = reader.nextEvent();
            if (e.isStartElement()) {
                final String element = e.asStartElement().getName().getLocalPart();
                if (element.equalsIgnoreCase("title")) {
                    final String name = reader.nextEvent().asCharacters().getData().trim();
                    for (final VersionInfo i : infos) {
                        if (name.equals(i.name)) {
                            current = i;
                            continue outer;
                        }
                    }
                    current = null;
                } else if (element.equalsIgnoreCase("description")) {
                    if (current == null)
                        continue;
                    final StringBuilder cl = new StringBuilder();
                    while ((e = reader.nextEvent()).isCharacters())
                        cl.append(e.asCharacters().getData());
                    current.changelog = "- " + StringEscapeUtils.unescapeHtml("" + cl).replace("<br>", "")
                            .replace("<p>", "").replace("</p>", "").replaceAll("\n(?!\n)", "\n- ");
                } else if (element.equalsIgnoreCase("pubDate")) {
                    if (current == null)
                        continue;
                    synchronized (RFC2822) { // to make FindBugs shut up
                        current.date = new Date(
                                RFC2822.parse(reader.nextEvent().asCharacters().getData()).getTime());
                    }
                }
            }
        }
    } catch (final IOException e) {
        stateLock.writeLock().lock();
        try {
            state = UpdateState.CHECK_ERROR;
            error.set(ExceptionUtils.toString(e));
            Skript.error(sender, m_check_error.toString());
        } finally {
            stateLock.writeLock().unlock();
        }
    } catch (final Exception e) {
        Skript.error(sender, m_internal_error.toString());
        Skript.exception(e, "Unexpected error while checking for a new version of Skript");
        stateLock.writeLock().lock();
        try {
            state = UpdateState.CHECK_ERROR;
            error.set(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
        } finally {
            stateLock.writeLock().unlock();
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
            }
        }
        if (r != null) {
            try {
                r.close();
            } catch (final IOException e) {
            }
        }
    }
}

From source file:com.threerings.getdown.util.ConnectionUtil.java

/**
 * Opens a connection to a URL, setting the authentication header if user info is present.
 *///  w ww  .  j a v a 2s.  com
public static URLConnection open(URL url) throws IOException {
    URLConnection conn = url.openConnection();

    // If URL has a username:password@ before hostname, use HTTP basic auth
    String userInfo = url.getUserInfo();
    if (userInfo != null) {
        // Remove any percent-encoding in the username/password
        userInfo = URLDecoder.decode(userInfo, "UTF-8");
        // Now base64 encode the auth info and make it a single line
        String encoded = Base64.encodeBase64String(userInfo.getBytes("UTF-8")).replaceAll("\\n", "")
                .replaceAll("\\r", "");
        conn.setRequestProperty("Authorization", "Basic " + encoded);
    }

    return conn;
}

From source file:at.gv.egiz.pdfas.web.helper.RemotePDFFetcher.java

public static byte[] fetchPdfFile(String pdfURL) throws PdfAsWebException {
    URL url;//from  w  w  w. jav  a2  s .  c o  m
    String[] fetchInfos;
    try {
        fetchInfos = extractSensitiveInformationFromURL(pdfURL);
        url = new URL(fetchInfos[0]);
    } catch (MalformedURLException e) {
        logger.warn("Not a valid URL!", e);
        throw new PdfAsWebException("Not a valid URL!", e);
    } catch (IOException e) {
        logger.warn("Not a valid URL!", e);
        throw new PdfAsWebException("Not a valid URL!", e);
    }
    if (WebConfiguration.isProvidePdfURLinWhitelist(url.toExternalForm())) {
        if (url.getProtocol().equals("http") || url.getProtocol().equals("https")) {
            URLConnection uc = null;
            InputStream is = null;
            try {
                uc = url.openConnection();

                if (fetchInfos.length == 3) {
                    String userpass = fetchInfos[1] + ":" + fetchInfos[2];
                    String basicAuth = "Basic "
                            + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8"));
                    uc.setRequestProperty("Authorization", basicAuth);
                }

                is = uc.getInputStream();
                return StreamUtils.inputStreamToByteArray(is);
            } catch (Exception e) {
                logger.warn("Failed to fetch pdf document!", e);
                throw new PdfAsWebException("Failed to fetch pdf document!", e);
            } finally {
                IOUtils.closeQuietly(is);
            }
        } else {
            throw new PdfAsWebException(
                    "Failed to fetch pdf document protocol " + url.getProtocol() + " is not supported");
        }
    } else {
        throw new PdfAsWebException("Failed to fetch pdf document " + url.toExternalForm() + " is not allowed");
    }
}

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

public static int cargarParadasLinea(Context context, int numeroLinea) {
    if (!isConnectionEnabled(context)) {
        return SIN_CONEXION;
    }// w  w  w . ja v  a2s  . c o m
    try {
        if (cookie == null) {
            if (loadCookie() == MANTENIMIENTO) {
                return MANTENIMIENTO;
            }
        }
        URL url = new URL(QUERY_ADDRESS_PARADAS_LINEA + numeroLinea);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + cookie);
        connection.setRequestProperty("REFERER", "http://m.surbus.com/tiempo-espera");
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        connection.connect();
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        JSONObject json = new JSONObject(strBuilder.toString());
        Log.d("Almeribus", strBuilder.toString());
        boolean isSuccessful = json.getBoolean("success");
        if (isSuccessful) {
            DataStorage.DBHelper.eliminarParadasLinea(numeroLinea);
            Linea l = new Linea(numeroLinea);
            JSONArray list = json.getJSONArray("list");
            Parada primeraParada = null;
            Parada paradaAnterior = null;
            for (int i = 0; i < list.length(); i++) {
                JSONObject paradaJSON = list.getJSONObject(i);
                int numeroParada = paradaJSON.getInt("IdBusStop");
                String nombreParada = paradaJSON.getString("Name");
                Parada p = null;
                if (DataStorage.paradas.containsKey(numeroParada)) {
                    p = DataStorage.paradas.get(numeroParada);
                    p.setNombre(nombreParada);
                } else {
                    p = new Parada(numeroParada, nombreParada);
                }
                synchronized (DataStorage.DBHelper) {
                    DataStorage.DBHelper.addInfoParada(numeroParada, nombreParada);
                }
                p.addLinea(l.getNumero());
                if (paradaAnterior != null) {
                    p.setAnterior(paradaAnterior.getId(), numeroLinea);
                }

                if (i == 0) {
                    primeraParada = p;
                } else if (i == list.length() - 1) {
                    primeraParada.setAnterior(p.getId(), numeroLinea);
                    p.setSiguiente(primeraParada.getId(), numeroLinea);
                }

                if (paradaAnterior != null) {
                    paradaAnterior.setSiguiente(p.getId(), numeroLinea);
                }

                paradaAnterior = p;
                synchronized (DataStorage.paradas) {
                    if (DataStorage.paradas.containsKey(numeroParada)) {
                        DataStorage.paradas.remove(numeroParada);
                    }
                    DataStorage.paradas.put(numeroParada, p);
                }

                l.addParada(p);
            }
            DataStorage.lineas.put(numeroLinea, l);
            for (Parada parada : l.getParadas()) {
                synchronized (DataStorage.DBHelper) {
                    try {
                        DataStorage.DBHelper.addParadaLinea(parada.getId(), numeroLinea,
                                parada.getSiguiente(numeroLinea));
                    } catch (ParadaNotFoundException e) {
                        DataStorage.DBHelper.addParadaLinea(parada.getId(), numeroLinea, 0);
                    }
                }
            }
            return TODO_OK;
        } else {
            return ERROR_IO;
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        return ERROR_IO;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return ERROR_IO;
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpLoader.java

public static synchronized void loadPolicy(Properties properties, StdPDPStatus status, String id,
        boolean isRoot) throws PAPException {
    PolicyDef policy = null;/*w  w  w  .j  av  a2  s. co m*/
    String location = null;
    URI locationURI = null;
    boolean isFile = false;
    try {
        location = properties.getProperty(id + ".file");
        if (location == null) {
            location = properties.getProperty(id + ".url");
            if (location != null) {
                //
                // Construct the URL
                //
                locationURI = URI.create(location);
                URL url = locationURI.toURL();
                URLConnection urlConnection = url.openConnection();
                urlConnection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID,
                        XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID));
                //
                // Now construct the output file name
                //
                Path outFile = Paths.get(getPDPConfig().toAbsolutePath().toString(), id);
                //
                // Copy it to disk
                //
                try (FileOutputStream fos = new FileOutputStream(outFile.toFile())) {
                    IOUtils.copy(urlConnection.getInputStream(), fos);
                }
                //
                // Now try to load
                //
                isFile = true;
                try (InputStream fis = Files.newInputStream(outFile)) {
                    policy = DOMPolicyDef.load(fis);
                }
                //
                // Save it
                //
                properties.setProperty(id + ".file", outFile.toAbsolutePath().toString());
            }
        } else {
            isFile = true;
            locationURI = Paths.get(location).toUri();
            try (InputStream is = Files.newInputStream(Paths.get(location))) {
                policy = DOMPolicyDef.load(is);
            }
        }
        if (policy != null) {
            status.addLoadedPolicy(new StdPDPPolicy(id, isRoot, locationURI, properties));
            logger.info("Loaded policy: " + policy.getIdentifier() + " version: "
                    + policy.getVersion().stringValue());
        } else {
            String error = "Failed to load policy " + location;
            logger.error(error);
            status.setStatus(PDPStatus.Status.LOAD_ERRORS);
            status.addLoadError(error);
            status.addFailedPolicy(new StdPDPPolicy(id, isRoot));
        }
    } catch (Exception e) {
        logger.error("Failed to load policy '" + id + "' from location '" + location + "'", e);
        status.setStatus(PDPStatus.Status.LOAD_ERRORS);
        status.addFailedPolicy(new StdPDPPolicy(id, isRoot));
        //
        // Is it a file?
        //
        if (isFile) {
            //
            // Let's remove it
            //
            try {
                logger.error("Corrupted policy file, deleting: " + location);
                Files.delete(Paths.get(location));
            } catch (IOException e1) {
                logger.error(e1);
            }
        }
        throw new PAPException("Failed to load policy '" + id + "' from location '" + location + "'");
    }
}

From source file:org.wso2.carbon.cloud.gateway.agent.CGAgentUtils.java

public static OMNode getOMElementFromURI(String wsdlURI) throws CGException {
    if (wsdlURI == null || "null".equals(wsdlURI)) {
        throw new CGException("Can't create URI from a null value");
    }//ww  w  .j av a 2s  .  c  om
    URL url;
    try {
        url = new URL(wsdlURI);
    } catch (MalformedURLException e) {
        throw new CGException("Invalid URI reference '" + wsdlURI + "'", e);
    }
    URLConnection connection;
    connection = getURLConnection(url);
    if (connection == null) {
        throw new CGException("Cannot create a URLConnection for given URL : " + url);
    }
    connection.setReadTimeout(getReadTimeout());
    connection.setConnectTimeout(getConnectTimeout());
    connection.setRequestProperty("Connection", "close"); // if http is being used
    InputStream inStream = null;

    try {
        inStream = connection.getInputStream();
        StAXOMBuilder builder = new StAXOMBuilder(inStream);
        OMElement doc = builder.getDocumentElement();
        doc.build();
        return doc;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Reading as XML failed due to ", e);
        }
        return readNonXML(url);
    } finally {
        try {
            if (inStream != null) {
                inStream.close();
            }
        } catch (IOException e) {
            log.warn("Error while closing the input stream to: " + url, e);
        }
    }
}