Java Code Examples for java.net.httpurlconnection#disconnect()

The following examples show how to use java.net.httpurlconnection#disconnect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExprUrlResponseCode.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
protected Integer[] get(Event e) {
  try {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection c = (HttpURLConnection) new URL(url.getSingle(e)).openConnection();
    c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    c.setRequestMethod("HEAD");
    int r = c.getResponseCode();
    c.disconnect();
    return new Integer[]{r};
  } catch (Exception x) {
    skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 2
Source File: ReadWSDLTest.java    From juddi with Apache License 2.0 6 votes vote down vote up
private static boolean IsReachable(String url) {
    System.out.println("Testing connectivity to " + url);
    try {
        //make a URL to a known source
        URL url2 = new URL(url);

        //open a connection to that source
        HttpURLConnection urlConnect = (HttpURLConnection) url2.openConnection();

        //trying to retrieve data from the source. If there
        //is no connection, this line will fail
        Object objData = urlConnect.getContent();
        urlConnect.disconnect();

    } catch (Exception e) {
        System.out.println("Connectivity failed " + e.getMessage());
        return false;
    }
    System.out.println("Connectivity passed" );
    return true;

}
 
Example 3
Source File: DownloadTask.java    From FimiX8-RE with MIT License 6 votes vote down vote up
private void startDownload() {
    File dir = new File(this.info.getPath());
    if (!dir.exists()) {
        dir.mkdirs();
    }
    File file = new File(this.info.getPath(), this.info.getDownloadFileName());
    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(this.info.getUrl()).openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream(file);
        CopyStream(is, os);
        save(this.info);
        os.close();
        conn.disconnect();
    } catch (Throwable ex) {
        ex.printStackTrace();
    }
    if (this.info.isDownloadFinish()) {
        this.listener.onSuccess(this.info);
    } else {
        this.listener.onFailure(this.info);
    }
}
 
Example 4
Source File: CardActivity.java    From LecteurOPUS with GNU General Public License v3.0 6 votes vote down vote up
private String sendHttpRequest(String url, String data) {
    StringBuffer buffer = new StringBuffer();
    try {
        System.out.println("URL ["+url+"] - Param ["+data+"]");

        HttpURLConnection con = (HttpURLConnection) ( new URL(url)).openConnection();
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.connect();
        con.getOutputStream().write( (data).getBytes());

        InputStream is = con.getInputStream();
        byte[] b = new byte[1024];

        while ( is.read(b) != -1)
            buffer.append(new String(b));

        con.disconnect();
    }
    catch(Throwable t) {
        t.printStackTrace();
    }

    return buffer.toString();
}
 
Example 5
Source File: SaslTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void cramMD5SASLAuthenticationWithMalformedResponse() throws Exception
{
    HttpURLConnection connection = requestSASLAuthentication(CramMd5Negotiator.MECHANISM);
    try
    {
        Map<String, Object> response = getHelper().readJsonResponseAsMap(connection);
        String challenge = (String) response.get("challenge");
        assertNotNull("Challenge is not found", challenge);

        List<String> cookies = connection.getHeaderFields().get(SET_COOKIE_HEADER);

        String responseData = Base64.getEncoder().encodeToString("null".getBytes());
        String requestParameters = String.format("id=%s&response=%s", response.get("id"), responseData);

        postResponse(cookies, requestParameters, SC_UNAUTHORIZED);

        assertAuthenticatedUser(null, cookies);
    }
    finally
    {
        connection.disconnect();
    }
}
 
Example 6
Source File: HttpServerTest.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAllFormItemsWithURLEncoded() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/getAllFormItemsURLEncoded", HttpMethod.POST);
    String rawData = "names=WSO2&names=IBM&age=10&type=Software";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals("No of Companies-2 type-Software", response);
}
 
Example 7
Source File: DeployUtil.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void createInfluxdbRetentionPolicy(String host, String port, String username, String password,
		String database, String retentionPeriod) {
	try {
		StringBuffer url = new StringBuffer();
		url.append(HTTP).append(host.trim()).append(COLON).append(port).append("/query?u=").append(username)
				.append(AND_P_EQUAL_TO).append(password).append(AND_Q_EQUAL_TO)
				.append("CREATE%20RETENTION%20POLICY%20ret_" + database + "%20on%20" + database + "%20DURATION%20"
						+ retentionPeriod + "d%20REPLICATION%201%20DEFAULT");

		URL obj = new URL(url.toString());
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("GET");
		con.setRequestProperty("User-Agent", "Mozilla/5.0");
		con.getContent();
		con.disconnect();
	} catch (Exception e) {
	}
}
 
Example 8
Source File: MojangUtils.java    From UhcCore with GNU General Public License v3.0 6 votes vote down vote up
public static UUID getPlayerUuid(String name){
    if (Bukkit.isPrimaryThread()){
        throw new RuntimeException("Requesting player UUID is not allowed on the primary thread!");
    }

    try {
        URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + name);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        JsonParser parser = new JsonParser();
        JsonElement json = parser.parse(new InputStreamReader(connection.getInputStream()));

        connection.disconnect();

        if (!json.isJsonObject()){
            return null;
        }

        String stringUuid = json.getAsJsonObject().get("id").getAsString();
        return insertDashUUID(stringUuid);
    }catch (IOException ex){
        ex.printStackTrace();
        return null;
    }
}
 
Example 9
Source File: AppUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Test passes when an {@link IOException} is thrown because this indicates that
 * the attacker caused the application to fail in some way. This does not
 * actually confirm that the exploit took place, because the RCE is a
 * side-effect that is difficult to observe.
 */
@Test(expected = SocketException.class)
public void givenAppIsVulneable_whenExecuteRemoteCodeWhichThrowsException_thenThrowsException() throws IOException {
    // POST the attack.xml to the application's /persons endpoint
    final URL url = new URL("http://localhost:" + app.port() + "/persons");
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestProperty("Content-Type", "application/xml");
    connection.connect();
    try (OutputStream os = connection.getOutputStream(); InputStream is = AppUnitTest.class.getResourceAsStream("/attack.xml")) {
        byte[] buffer = new byte[1024];
        while (is.read(buffer) > 0) {
            os.write(buffer);
        }
    }
    final int rc = connection.getResponseCode();
    connection.disconnect();
    assertTrue(rc >= 400);
}
 
Example 10
Source File: HttpServerTest.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormParamWithFile() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/testFormParamWithFile", HttpMethod.POST);
    File file = new File(Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").toURI());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    builder.addPart("form", fileBody);
    HttpEntity build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, file.getName());
}
 
Example 11
Source File: HickwallClient.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected void closeIfNotValidConnect(HttpURLConnection httpURLConnection) throws IOException {
    if (httpURLConnection == null) {
        return;
    }
    InputStream in = httpURLConnection.getErrorStream();
    if (in != null) {
        in.close();
        httpURLConnection.disconnect();
        this.connection = null;
    }
}
 
Example 12
Source File: MyDownload.java    From AppUpdate with Apache License 2.0 5 votes vote down vote up
@Override
public void download(final String apkUrl, final String apkName, final OnDownloadListener listener) {
    listener.start();
    try {
        URL url = new URL(apkUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setReadTimeout(Constant.HTTP_TIME_OUT);
        con.setConnectTimeout(Constant.HTTP_TIME_OUT);
        if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream is = con.getInputStream();
            int length = con.getContentLength();
            int len;
            //当前已下载完成的进度
            int progress = 0;
            byte[] buffer = new byte[1024 * 4];
            File file = FileUtil.createFile(Environment.getExternalStorageDirectory() + "/AppUpdate", apkName);
            FileOutputStream stream = new FileOutputStream(file);
            while ((len = is.read(buffer)) != -1) {
                //将获取到的流写入文件中
                stream.write(buffer, 0, len);
                progress += len;
                listener.downloading(length, progress);
            }
            //完成io操作,释放资源
            stream.flush();
            stream.close();
            is.close();
            listener.done(file);
        } else {
            listener.error(new SocketTimeoutException("连接超时!"));
        }
        con.disconnect();
    } catch (Exception e) {
        listener.error(e);
        e.printStackTrace();
    }

}
 
Example 13
Source File: SwaggerTest.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceSwagger() throws Exception {
    HttpURLConnection urlConn = request("/swagger?path=/test/v1", HttpMethod.GET);
    assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode());
    assertEquals(MediaType.APPLICATION_JSON, urlConn.getHeaderField(HttpHeaders.CONTENT_TYPE));
    urlConn.disconnect();
}
 
Example 14
Source File: MediaWikiClient.java    From git-changelog-lib with Apache License 2.0 5 votes vote down vote up
private void createPage(HttpState httpState, String url, String title, String text)
    throws Exception {
  final URL wikiurl = new URL(url + "/api.php");
  final HttpURLConnection conn = openConnection(wikiurl);
  try {
    conn.setRequestMethod("POST");

    final Map<String, String> params = newHashMap();
    params.put("format", "json");
    params.put("token", httpState.getEditToken());
    params.put("action", "edit");
    params.put("title", title);
    params.put("summary", "Git Changelog Plugin");
    params.put("text", escapeXml(text));
    if (httpState.getCookieString().isPresent()) {
      conn.setRequestProperty("Cookie", httpState.getCookieString().get());
    }
    conn.setDoOutput(true);
    conn.connect();

    final StringBuilder querySb = new StringBuilder();
    for (final Entry<String, String> e : params.entrySet()) {
      querySb.append("&" + e.getKey() + "=" + encode(e.getValue(), UTF_8.name()));
    }
    final String query = querySb.toString().substring(1);

    final OutputStream output = conn.getOutputStream();
    output.write(query.getBytes(UTF_8.name()));
    final String response = getResponse(conn);
    logger.info("Got: " + response);
  } finally {
    conn.disconnect();
  }
}
 
Example 15
Source File: MediaThumDownloadTask.java    From FimiX8-RE with MIT License 5 votes vote down vote up
private void startDownload() {
    String path = "";
    String fileName = "";
    String urlPath = "";
    path = this.model.getLocalThumFileDir();
    urlPath = this.model.getThumFileUrl();
    this.model.setDownloadName(String.valueOf(urlPath.hashCode()));
    fileName = this.model.getDownloadName();
    File dir = new File(path);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    File file = new File(path, fileName);
    if (file.exists()) {
        this.listener.onSuccess(this.model);
        return;
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(urlPath).openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream(file);
        CopyStream(is, os);
        save(this.model);
        os.close();
        conn.disconnect();
    } catch (Throwable ex) {
        ex.printStackTrace();
    }
    if (this.model.isThumDownloadFinish()) {
        this.listener.onSuccess(this.model);
    } else {
        this.listener.onFailure(this.model);
    }
}
 
Example 16
Source File: BasicBoundFunctionITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void boundFunctionETIsComposibleOrderBy() throws Exception {
  URL url = new URL(SERVICE_URI + "ESTwoKeyNav/olingo.odata.test1.BFESTwoKeyNavRTESTwoKeyNav()?"
      + "$orderby=PropertyInt16%20desc");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
  connection.disconnect();
}
 
Example 17
Source File: BasicBoundFunctionITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void boundFunctionReturningNavigationType() throws Exception {
  URL url = new URL(SERVICE_URI + "ESTwoKeyNav(PropertyInt16=1,PropertyString='1')"
      + "/NavPropertyETTwoKeyNavMany/olingo.odata.test1.BFC_RTESTwoKeyNav_()");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  final String expected =    "\"PropertyCompNav\":{"
      +             "\"PropertyInt16\":1,"
      +             "\"PropertyComp\":{"
      +             "\"PropertyString\":\"First Resource - positive values\","
      +             "\"PropertyBinary\":\"ASNFZ4mrze8=\","
      +             "\"PropertyBoolean\":true,"
      +             "\"PropertyByte\":255,"
      +             "\"PropertyDate\":\"2012-12-03\","
      +             "\"PropertyDateTimeOffset\":\"2012-12-03T07:16:23Z\","
      +             "\"PropertyDecimal\":34,"
      +             "\"PropertySingle\":1.79E20,"
      +             "\"PropertyDouble\":-1.79E20,"
      +             "\"PropertyDuration\":\"PT6S\","
      +             "\"PropertyGuid\":\"01234567-89ab-cdef-0123-456789abcdef\","
      +             "\"PropertyInt16\":32767,"
      +             "\"PropertyInt32\":2147483647,"
      +             "\"PropertyInt64\":9223372036854775807,"
      +             "\"PropertySByte\":127,"
      +             "\"PropertyTimeOfDay\":\"21:05:59\"";
  String content = IOUtils.toString(connection.getInputStream());
  assertTrue(content.contains(expected));
  connection.disconnect();
}
 
Example 18
Source File: DomainGracefulShutdownTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testGracefulShutdownDomainLevel() throws Exception {
    DomainClient client = domainMasterLifecycleUtil.getDomainClient();

    final String address = "http://" + TestSuiteEnvironment.getServerAddress() + ":8080/web-suspend";
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    try {
        Future<Object> result = executorService.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return HttpRequest.get(address, 60, TimeUnit.SECONDS);
            }
        });

        Thread.sleep(1000); //nasty, but we need to make sure the HTTP request has started

        ModelNode op = new ModelNode();
        op.get(ModelDescriptionConstants.OP).set("stop-servers");
        op.get(ModelDescriptionConstants.TIMEOUT).set(60);
        op.get(ModelDescriptionConstants.BLOCKING).set(false);
        client.execute(op);

        //make sure requests are being rejected
        final HttpURLConnection conn = (HttpURLConnection) new URL(address).openConnection();
        try {
            conn.setDoInput(true);
            int responseCode = conn.getResponseCode();
            Assert.assertEquals(503, responseCode);
        } finally {
            conn.disconnect();
        }

        //make sure the server is still up, and trigger the actual shutdown
        HttpRequest.get(address + "?" + TestUndertowService.SKIP_GRACEFUL + "=true", 10, TimeUnit.SECONDS);
        Assert.assertEquals(SuspendResumeHandler.TEXT, result.get());

        //make sure our initial request completed
        Assert.assertEquals(SuspendResumeHandler.TEXT, result.get());


    } finally {
        executorService.shutdown();
    }
}
 
Example 19
Source File: HurlStack.java    From volley with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<>();
    map.putAll(additionalHeaders);
    // Request.getHeaders() takes precedence over the given additional (cache) headers).
    map.putAll(request.getHeaders());
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    boolean keepConnectionOpen = false;
    try {
        for (String headerName : map.keySet()) {
            connection.setRequestProperty(headerName, map.get(headerName));
        }
        setConnectionParametersForRequest(connection, request);
        // Initialize HttpResponse with data from the HttpURLConnection.
        int responseCode = connection.getResponseCode();
        if (responseCode == -1) {
            // -1 is returned by getResponseCode() if the response code could not be retrieved.
            // Signal to the caller that something was wrong with the connection.
            throw new IOException("Could not retrieve response code from HttpUrlConnection.");
        }

        if (!hasResponseBody(request.getMethod(), responseCode)) {
            return new HttpResponse(responseCode, convertHeaders(connection.getHeaderFields()));
        }

        // Need to keep the connection open until the stream is consumed by the caller. Wrap the
        // stream such that close() will disconnect the connection.
        keepConnectionOpen = true;
        return new HttpResponse(
                responseCode,
                convertHeaders(connection.getHeaderFields()),
                connection.getContentLength(),
                createInputStream(request, connection));
    } finally {
        if (!keepConnectionOpen) {
            connection.disconnect();
        }
    }
}
 
Example 20
Source File: AgentClient.java    From jxapi with Apache License 2.0 4 votes vote down vote up
protected String issueProfilePut(String path, String data, HashMap<String, String> etag)
        throws java.io.IOException {
	URL url = new URL(this._host.getProtocol(), this._host.getHost(), this._host.getPort(), this._host.getPath()+path);

    HttpURLConnection conn = initializeConnection(url);
    conn.setRequestMethod("POST");

    // Agent Profile requires either of these headers being sent
    // If neither are sent it will set If-None-Match to null and exception
    // will be caught during request
    if (etag.containsKey("If-Match")){
        conn.addRequestProperty("If-Match", etag.get("If-Match"));
    }
    else{
        conn.addRequestProperty("If-None-Match", etag.get("If-None-Match"));
    }

    conn.setRequestMethod("PUT");
    OutputStreamWriter writer = new OutputStreamWriter(
            conn.getOutputStream());
    try {
        writer.write(data);
    } catch (IOException ex) {
        InputStream s = conn.getErrorStream();
        InputStreamReader isr = new InputStreamReader(s);
        BufferedReader br = new BufferedReader(isr);
        try {
            String line;
            while((line = br.readLine()) != null){
                System.out.print(line);
            }
            System.out.println();
        } finally {
            s.close();
        }
        throw ex;
    } finally {
        writer.close();
    }
    try {
        return readFromConnection(conn);
    } finally {
        conn.disconnect();
    }
}