Example usage for java.net HttpURLConnection disconnect

List of usage examples for java.net HttpURLConnection disconnect

Introduction

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

Prototype

public abstract void disconnect();

Source Link

Document

Indicates that other requests to the server are unlikely in the near future.

Usage

From source file:Main.java

public static String customrequest(String url, HashMap<String, String> params, String method) {
    try {//from  w  ww .  j  a  v a 2 s.c om

        URL postUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(5 * 1000);

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");

        conn.connect();
        OutputStream out = conn.getOutputStream();
        StringBuilder sb = new StringBuilder();
        if (null != params) {
            int i = params.size();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (i == 1) {
                    sb.append(entry.getKey() + "=" + entry.getValue());
                } else {
                    sb.append(entry.getKey() + "=" + entry.getValue() + "&");
                }

                i--;
            }
        }
        String content = sb.toString();
        out.write(content.getBytes("UTF-8"));
        out.flush();
        out.close();
        InputStream inStream = conn.getInputStream();
        String result = inputStream2String(inStream);
        conn.disconnect();
        return result;
    } catch (Exception e) {
        // TODO: handle exception
    }
    return null;
}

From source file:com.orchestra.portale.external.services.manager.CiRoService.java

@Override
public String getResponse(Map<String, String[]> mapParams) {
    try {//from w w  w .j a  v a  2 s. com
        HttpURLConnection urlConnection = (HttpURLConnection) new URL(getUrl).openConnection();
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(30000);
        urlConnection.addRequestProperty("Accept-Language", Locale.getDefault().toString().replace('_', '-'));
        String result = IOUtils.toString(urlConnection.getInputStream());
        urlConnection.disconnect();
        return result;
    } catch (IOException e) {
        return "response{code:1,error:" + e.getMessage() + "}";
    }
}

From source file:org.jenkinsci.plugins.url_auth.UrlSecurityRealm.java

@Override
protected UserDetails authenticate(String username, String password) throws AuthenticationException {
    try {/* w  w  w.j  a  va2s.  c o  m*/
        if (username == null || password == null || username.trim().isEmpty() || password.trim().isEmpty()) {
            throw new BadCredentialsException("Username or password can't be empty.");
        }
        String urlString = loginUrl.replace("[username]", username).replace("[password]", password);
        //System.out.println(urlString);
        URL iurl = new URL(urlString);
        HttpURLConnection uc;
        if (testConnection == null) {
            uc = (HttpURLConnection) iurl.openConnection();
        } else {
            uc = testConnection;
        }
        uc.connect();
        if (this.useResponseCode) {
            int response = uc.getResponseCode();
            uc.disconnect();
            if (response != successResponse) {
                throw new BadCredentialsException(
                        String.format("Response %d didn't match %d", response, this.successResponse));
            }
        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));

            String matchLine = in.readLine().toLowerCase();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                matchLine = matchLine.concat(inputLine);
            }
            matchLine = matchLine.trim().toLowerCase();
            System.out.println(matchLine);
            in.close();
            uc.disconnect();
            if (matchLine == null ? this.successString.toLowerCase() != null
                    : !matchLine.equals(this.successString.toLowerCase())) {
                throw new BadCredentialsException(
                        String.format("Response %s didn't match %s", matchLine, this.successString));
            }
        }
        GrantedAuthority[] groups = new GrantedAuthority[0];
        UserDetails d = new User(username, password, true, true, true, true, groups);
        return d;
    } catch (Exception e) {
        throw new AuthenticationServiceException("Failed", e);
    }
}

From source file:com.github.gilbertotorrezan.viacep.se.ViaCEPClient.java

/**
 * Executa a consulta de endereos a partir da UF, localidade e logradouro
 * //  w w  w  . ja  va  2 s .com
 * @param uf Unidade Federativa. Precisa ter 2 caracteres.
 * @param localidade Localidade (p.e. municpio). Precisa ter ao menos 3 caracteres.
 * @param logradouro Logradouro (p.e. rua, avenida, estrada). Precisa ter ao menos 3 caracteres.
 * 
 * @return Os endereos encontrado para os dados enviados, nunca <code>null</code>. Caso no sejam encontrados endereos, uma lista vazia  retornada.
 * @throws IOException em casos de erro de conexo.
 * @throws IllegalArgumentException para localidades e logradouros com tamanho menor do que 3 caracteres.
 */
public List<ViaCEPEndereco> getEnderecos(String uf, String localidade, String logradouro) throws IOException {
    if (uf == null || uf.length() != 2) {
        throw new IllegalArgumentException("UF invlida - deve conter 2 caracteres: " + uf);
    }
    if (localidade == null || localidade.length() < 3) {
        throw new IllegalArgumentException(
                "Localidade invlida - deve conter pelo menos 3 caracteres: " + localidade);
    }
    if (logradouro == null || logradouro.length() < 3) {
        throw new IllegalArgumentException(
                "Logradouro invlido - deve conter pelo menos 3 caracteres: " + logradouro);
    }

    String urlString = getHost() + uf + "/" + localidade + "/" + logradouro + "/json/";
    URL url = new URL(urlString);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        List<ViaCEPEndereco> obj = getService().listOfFrom(ViaCEPEndereco.class, in);
        return obj;
    } finally {
        urlConnection.disconnect();
    }
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Upload ontology content on specified dataset. Graph used is the default
 * one except if specified/*from   ww w.j  a v a2s . c  o m*/
 * 
 * @param ontology
 * @param datasetName
 * @param graphName
 * @throws IOException
 * @throws HttpException
 */
public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName)
        throws IOException, HttpException {
    graphName = Strings.emptyToNull(graphName);

    logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName));

    boolean createGraph = (graphName != null) ? true : false;
    String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8");
    String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null;

    URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : ""));

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

    String boundary = "------------------" + System.currentTimeMillis()
            + Long.toString(Math.round(Math.random() * 1000));

    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConnection.setRequestProperty("Connection", "keep-alive");
    httpConnection.setRequestProperty("Cache-Control", "no-cache");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write(BOUNDARY_DECORATOR + boundary + EOL);
    out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL);
    out.write("Content-Type: application/octet-stream" + EOL + EOL);
    out.write(CharStreams.toString(new InputStreamReader(ontology)));
    out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL);
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_CREATED:
        checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }

}

From source file:KV78Tester.java

public void checkLines(String[] lines) throws IOException {
    System.out.println("Checking " + lines.length + " lines");
    for (int i = 0; i < lines.length; i++) {
        String uri = "http://openov.nl:5078/line/" + lines[i];
        URL url = new URL(uri);
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("User-Agent", "KV78Turbo-Test");
        uc.setConnectTimeout(60000);/*  ww w. jav a2  s  .  c o m*/
        uc.setReadTimeout(60000);
        BufferedReader in;
        in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
        try {
            checkLines(in);
        } finally {
            uc.disconnect();
        }
    }
}

From source file:com.mebigfatguy.polycasso.URLFetcher.java

/**
 * retrieve arbitrary data found at a specific url
 * - either http or file urls/*from ww w  .j a  va  2 s  .c om*/
 * for http requests, sets the user-agent to mozilla to avoid
 * sites being cranky about a java sniffer
 * 
 * @param url the url to retrieve
 * @param proxyHost the host to use for the proxy
 * @param proxyPort the port to use for the proxy
 * @return a byte array of the content
 * 
 * @throws IOException the site fails to respond
 */
public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException {
    HttpURLConnection con = null;
    InputStream is = null;

    try {
        URL u = new URL(url);
        if (url.startsWith("file://")) {
            is = new BufferedInputStream(u.openStream());
        } else {
            Proxy proxy;
            if (proxyHost != null) {
                proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            } else {
                proxy = Proxy.NO_PROXY;
            }
            con = (HttpURLConnection) u.openConnection(proxy);
            con.addRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6");
            con.addRequestProperty("Accept-Charset", "UTF-8");
            con.addRequestProperty("Accept-Language", "en-US,en");
            con.addRequestProperty("Accept", "text/html,image/*");
            con.setDoInput(true);
            con.setDoOutput(false);
            con.connect();

            is = new BufferedInputStream(con.getInputStream());
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(is, baos);
        return baos.toByteArray();
    } finally {
        IOUtils.closeQuietly(is);
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:AddressSvc.AddressSvc.java

public ValidateResult Validate(Address address) {

    //Create query/url
    String queryparams = address.toQuery();
    String addrval = svcURL + "/1.0/address/validate?" + queryparams;
    URL url;/*  ww  w  .j a va2s .  c  o m*/

    HttpURLConnection conn;
    try {
        //Connect to specified URL with authorization header
        url = new URL(addrval);
        conn = (HttpURLConnection) url.openConnection();
        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.disconnect();

        ObjectMapper mapper = new ObjectMapper(); //Deserialization object

        if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error
        {
            ValidateResult vres = mapper.readValue(conn.getErrorStream(), ValidateResult.class); //Deserializes the response object
            return vres;
        }

        else //Otherwise, print out the validated address.
        {
            ValidateResult vres = mapper.readValue(conn.getInputStream(), ValidateResult.class); //Deserializes the response object
            return vres;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test method for.//from  w  ww  . j  a v a2s .  co  m
 *
 * @throws Exception the exception
 * {@link ext.services.network.NetworkUtils#readURL(java.net.URLConnection)}.
 */
public void testReadURLURLConnection() throws Exception {
    HttpURLConnection connection = NetworkUtils.getConnection(URL, null);
    assertNotNull(connection);
    String str = NetworkUtils.readURL(connection);
    assertNotNull(str);
    assertTrue(StringUtils.isNotBlank(str));
    connection.disconnect();
}

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test read urlurl connection string disabled.
 * /*w  ww  . j  av  a2 s.  c  o m*/
 *
 * @throws Exception the exception
 */
public void testReadURLURLConnectionStringDisabled() throws Exception {
    HttpURLConnection connection = NetworkUtils.getConnection(URL, null);
    assertNotNull(connection);
    Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "true");
    assertNull(NetworkUtils.readURL(connection, "UTF-8"));
    connection.disconnect();
}