Java Code Examples for java.net.HttpURLConnection#connect()

The following examples show how to use java.net.HttpURLConnection#connect() . 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: DiscordService.java    From Game with GNU General Public License v3.0 6 votes vote down vote up
private static void sendToDiscord(final String webhookUrl, final String message) throws Exception {
	final StringBuilder sb = new StringBuilder();
	JsonUtils.quoteAsString(message, sb);

	final String jsonPostBody = String.format("{\"content\": \"%s\"}", sb);

	final java.net.URL url = new java.net.URL(webhookUrl);

	final URLConnection con = url.openConnection();
	final HttpURLConnection http = (HttpURLConnection) con;
	http.setRequestMethod("POST");
	http.setDoOutput(true);

	final byte[] out = jsonPostBody.getBytes(StandardCharsets.UTF_8);
	final int length = out.length;

	http.setFixedLengthStreamingMode(length);
	http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
	try {
		http.connect();
		try (OutputStream os = http.getOutputStream()) {
			os.write(out);
		}
	}
	catch (Exception e) {
		LOGGER.error(e);
	}
}
 
Example 2
Source File: TestHttpFSServer.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Talks to the http interface to create a file.
 *
 * @param filename The file to create
 * @param perms The permission field, if any (may be null)
 * @throws Exception
 */
private void createWithHttp ( String filename, String perms )
        throws Exception {
  String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
  // Remove leading / from filename
  if ( filename.charAt(0) == '/' ) {
    filename = filename.substring(1);
  }
  String pathOps;
  if ( perms == null ) {
    pathOps = MessageFormat.format(
            "/webhdfs/v1/{0}?user.name={1}&op=CREATE",
            filename, user);
  } else {
    pathOps = MessageFormat.format(
            "/webhdfs/v1/{0}?user.name={1}&permission={2}&op=CREATE",
            filename, user, perms);
  }
  URL url = new URL(TestJettyHelper.getJettyURL(), pathOps);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.addRequestProperty("Content-Type", "application/octet-stream");
  conn.setRequestMethod("PUT");
  conn.connect();
  Assert.assertEquals(HttpURLConnection.HTTP_CREATED, conn.getResponseCode());
}
 
Example 3
Source File: HttpClientRequestImpl.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to the remote server.
 */
private void connect() {
    try {
        URL url = new URL(this.endpoint);
        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(this.readTimeoutMs);
        connection.setConnectTimeout(this.connectTimeoutMs);
        connection.setRequestMethod(this.method.name());
        if (method == HttpMethod.POST || method == HttpMethod.PUT) {
            connection.setDoOutput(true);
        } else {
            connection.setDoOutput(false);
        }
        connection.setDoInput(true);
        connection.setUseCaches(false);
        for (String headerName : headers.keySet()) {
            String headerValue = headers.get(headerName);
            connection.setRequestProperty(headerName, headerValue);
        }
        connection.connect();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: MasterTemplateLoader.java    From CloudNet with Apache License 2.0 6 votes vote down vote up
public MasterTemplateLoader load() {
    try {
        HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("-Xcloudnet-user", simpledUser.getUserName());
        urlConnection.setRequestProperty("-Xcloudnet-token", simpledUser.getApiToken());
        urlConnection.setRequestProperty("-Xmessage", customName != null ? "custom" : "template");
        urlConnection.setRequestProperty("-Xvalue", customName != null ? customName : new Document("template",
                                                                                                   template.getName()).append("group",
                                                                                                                              group)
                                                                                                                      .convertToJsonString());
        urlConnection.setUseCaches(false);
        urlConnection.connect();

        if (urlConnection.getHeaderField("-Xresponse") == null) {
            Files.copy(urlConnection.getInputStream(), Paths.get(dest));
        }

        urlConnection.disconnect();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return this;
}
 
Example 5
Source File: KerberosWebHDFSConnection.java    From Transwarp-Sample-Code with MIT License 6 votes vote down vote up
/**
 * <b>GETFILECHECKSUM</b>
 *
 * curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=GETFILECHECKSUM"
 *
 * @param path
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String getFileCheckSum(String path) throws MalformedURLException,
        IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();

    HttpURLConnection conn = authenticatedURL.openConnection(
            new URL(new URL(httpfsUrl), MessageFormat.format(
                    "/webhdfs/v1/{0}?delegation="+delegation+"&op=GETFILECHECKSUM",
                    URLUtil.encodePath(path))), token);

    conn.setRequestMethod("GET");
    conn.connect();
    resp = result(conn, true);
    conn.disconnect();

    return resp;
}
 
Example 6
Source File: RestStressTestClient.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public int put(String restServiceUrl, Map<String, Object> attributes) throws IOException
{
    HttpURLConnection connection = createConnection("PUT", restServiceUrl, _cookies);
    try
    {
        connection.connect();
        if (attributes != null)
        {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(connection.getOutputStream(), attributes);
        }
        checkResponseCode(connection);
        return connection.getResponseCode();
    }
    finally
    {
        connection.disconnect();
    }
}
 
Example 7
Source File: DefaultImageDownloader.java    From RichText with MIT License 6 votes vote down vote up
@Override
public InputStream getInputStream() throws IOException {
    URL url = new URL(this.url);
    connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(10000);
    connection.setDoInput(true);
    connection.addRequestProperty("Connection", "Keep-Alive");

    if (connection instanceof HttpsURLConnection) {
        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;
        httpsURLConnection.setHostnameVerifier(DO_NOT_VERIFY);
        httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    connection.connect();

    int responseCode = connection.getResponseCode();
    if (responseCode == 200) {
        inputStream = connection.getInputStream();
        return inputStream;
    } else {
        throw new HttpResponseCodeException(responseCode);
    }
}
 
Example 8
Source File: KerberosWebHDFSConnection.java    From Transwarp-Sample-Code with MIT License 6 votes vote down vote up
/**
 * <b>MKDIRS</b>
 *
 * curl -i -X PUT
 * "http://<HOST>:<PORT>/<PATH>?op=MKDIRS[&permission=<OCTAL>]"
 *
 * @param path
 * @return
 * @throws AuthenticationException
 * @throws IOException
 * @throws MalformedURLException
 */
public String mkdirs(String path) throws MalformedURLException,
        IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();

    HttpURLConnection conn = authenticatedURL
            .openConnection(
                    new URL(new URL(httpfsUrl), MessageFormat.format(
                            "/webhdfs/v1/{0}?delegation="+delegation+"&op=MKDIRS",
                            URLUtil.encodePath(path))), token);
    conn.setRequestMethod("PUT");
    conn.connect();
    resp = result(conn, true);
    conn.disconnect();

    return resp;
}
 
Example 9
Source File: DriveUploader.java    From cloud-transfer-backend with MIT License 6 votes vote down vote up
/**
 * It will upload bytes in range [start,end] to Google drive.
 *
 * @param start
 *            starting byte of range
 * @param end
 *            ending byte of range
 */
void uploadPartially(@NotNull byte[] buffer, long start, long end) {
	String contentRange = "bytes " + start + "-" + end + "/" + downloadFileInfo.getContentLength();

	int statusCode;
	try {
		HttpURLConnection uploadConnection = (HttpURLConnection) createdFileUrl.openConnection();
		uploadConnection.setDoOutput(true);
		uploadConnection.setRequestProperty("User-Agent", USER_AGENT);
		uploadConnection.setRequestProperty("Content-Range", contentRange);
		IOUtils.copy(new ByteArrayInputStream(buffer), uploadConnection.getOutputStream());
		uploadConnection.connect();
		statusCode = uploadConnection.getResponseCode();
	} catch (IOException e) {
		throw new RuntimeException("Error While uploading file.", e);
	}

	// In case of successful upload, status code will be 3** or 2**
	if (statusCode < 400)
		uploadInformation.setUploadedSize(end + 1);
	else if (statusCode == 403) {
		throw new RuntimeException(
				"Google didn't allow us to create file. Your drive might not have enough space.");
	}
}
 
Example 10
Source File: MetricParameters.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private String readGceMetadata(String path) {
  String value = "";
  HttpURLConnection connection = connectionFactory.apply(path);
  try {
    connection.connect();
    int responseCode = connection.getResponseCode();
    if (responseCode < 200 || responseCode > 299) {
      logger.atWarning().log(
          "Got an error response: %d\n%s",
          responseCode,
          CharStreams.toString(new InputStreamReader(connection.getErrorStream(), UTF_8)));
    } else {
      value = CharStreams.toString(new InputStreamReader(connection.getInputStream(), UTF_8));
    }
  } catch (IOException e) {
    logger.atWarning().withCause(e).log("Cannot obtain GCE metadata from path %s", path);
  }
  return value;
}
 
Example 11
Source File: TestRMFailover.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testWebAppProxyInStandAloneMode() throws YarnException,
    InterruptedException, IOException {
  conf.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false);
  WebAppProxyServer webAppProxyServer = new WebAppProxyServer();
  try {
    conf.set(YarnConfiguration.PROXY_ADDRESS, "0.0.0.0:9099");
    cluster.init(conf);
    cluster.start();
    getAdminService(0).transitionToActive(req);
    assertFalse("RM never turned active", -1 == cluster.getActiveRMIndex());
    verifyConnections();
    webAppProxyServer.init(conf);

    // Start webAppProxyServer
    Assert.assertEquals(STATE.INITED, webAppProxyServer.getServiceState());
    webAppProxyServer.start();
    Assert.assertEquals(STATE.STARTED, webAppProxyServer.getServiceState());

    // send httpRequest with fakeApplicationId
    // expect to get "Not Found" response and 404 response code
    URL wrongUrl = new URL("http://0.0.0.0:9099/proxy/" + fakeAppId);
    HttpURLConnection proxyConn = (HttpURLConnection) wrongUrl
        .openConnection();

    proxyConn.connect();
    verifyResponse(proxyConn);

    explicitFailover();
    verifyConnections();
    proxyConn.connect();
    verifyResponse(proxyConn);
  } finally {
    webAppProxyServer.stop();
  }
}
 
Example 12
Source File: PlexAuthenticationService.java    From proxylive with MIT License 5 votes vote down vote up
@Scheduled(fixedDelay = 30 * 1000)//Every 30 seconds
public void refreshPlexUsers() throws IOException {
    PlexAuthentication plexAuthConfig = configuration.getAuthentication().getPlex();
    if(new Date().getTime()-lastUpdate>+(plexAuthConfig.getRefresh()*1000)) {
        List<String> allowedUsers = new ArrayList();
        allowedUsers.add(plexAuthConfig.getAdminUser());
        URL url = new URL(String.format("https://%s:%[email protected]/api/users", URLEncoder.encode(plexAuthConfig.getAdminUser(), "UTF-8"), URLEncoder.encode(plexAuthConfig.getAdminPass(), "UTF-8")));
        HttpURLConnection connection = createConnection(url);
        connection.connect();
        if (connection.getResponseCode() != 200) {
            throw new IOException("unexpected error when getting users list:" + connection.getResponseCode());
        }
        Document dom = newDocumentFromInputStream(connection.getInputStream());
        NodeList users = dom.getElementsByTagName("User");
        for (int i = 0; i < users.getLength(); i++) {
            Element userEl = (Element) users.item(i);
            NodeList servers = userEl.getElementsByTagName("Server");
            if (servers.getLength() > 0) {
                for (int j = 0; j < servers.getLength(); j++) {
                    Element server = (Element) servers.item(j);
                    if (server.getAttribute("name").equals(plexAuthConfig.getServerName())) {
                        allowedUsers.add(userEl.getAttribute("username").toLowerCase());
                    }
                }
            }
        }
        this.lastUpdate=new Date().getTime();
        this.allowedUsers = allowedUsers;
    }
}
 
Example 13
Source File: HttpRequestUtil.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
/** 
 * 发送http请求取得返回的输入流 
 * @param requestUrl 请求地址 
 * @return InputStream 
 * @throws IOException 
 */
public static InputStream httpRequestIO(String requestUrl) throws IOException {
    URL url = new URL(requestUrl);
    HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
    httpUrlConn.setDoInput(true);
    httpUrlConn.setRequestMethod("GET");
    httpUrlConn.connect();
    // 获得返回的输入流 
    InputStream inputStream = httpUrlConn.getInputStream();
    return inputStream;
}
 
Example 14
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void validFormatWithIncorrectAcceptCharsetHeader() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim?$format=json");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf<8");
  connection.connect();

  assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());

  final String content = IOUtils.toString(connection.getErrorStream());
  assertTrue(content.contains("The Accept charset header 'utf<8' is not supported."));
}
 
Example 15
Source File: BasicBoundFunctionITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void boundFunctionOverload() throws Exception {
  URL url = new URL(SERVICE_URI + "ESTwoKeyNav/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());
  String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
  connection.disconnect();
}
 
Example 16
Source File: WelcomeActivity.java    From iMoney with Apache License 2.0 5 votes vote down vote up
/**
 * 下载对应url下的apk文件
 */
private void downloadAPK() throws Exception {
    FileOutputStream fos = new FileOutputStream(apkFile);
    String path = updateInfo.apkUrl;
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);
    conn.setRequestMethod("GET");
    conn.connect();

    if (conn.getResponseCode() == 200) {
        InputStream is = conn.getInputStream();
        dialog.setMax(conn.getContentLength());
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
            dialog.incrementProgressBy(len);
            Thread.sleep(2);
        }
        // 暂且使用throws的方式处理异常了
        is.close();
        fos.close();
    } else {
        handler.sendEmptyMessage(WHAT_DOWNLOAD_FAIL);
    }
    // 关闭连接
    conn.disconnect();
}
 
Example 17
Source File: InOperatorITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void queryInOperatorOnNavProperty() throws Exception {
  URL url = new URL(SERVICE_URI + "ESKeyNav?$filter=PropertyCompTwoPrim/"
      + "PropertyInt16%20in%20NavPropertyETKeyNavOne/CollPropertyInt16");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=minimal");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE)));

  final String content = IOUtils.toString(connection.getInputStream());
  assertTrue(content.contains("\"value\":[]"));
}
 
Example 18
Source File: GetGeoFromRedirectUri.java    From LocationPrivacy with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected String doInBackground(Void... params) {
    String result = null;
    HttpURLConnection connection = null;
    try {
        connection = NetCipher.getHttpURLConnection(this.urlString);
        connection.setRequestMethod("HEAD");
        connection.setInstanceFollowRedirects(false);
        // gzip encoding seems to cause problems
        // https://code.google.com/p/android/issues/detail?id=24672
        connection.setRequestProperty("Accept-Encoding", "");
        connection.connect();
        connection.getResponseCode(); // this actually makes it go
        String uriString = connection.getHeaderField("Location");
        if (!TextUtils.isEmpty(uriString)) {
            GeoParsedPoint point = GeoPointParserUtil.parse(uriString);
            if (point != null)
                result = point.getGeoUriString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null)
            connection.disconnect();
    }
    return result;
}
 
Example 19
Source File: MainFragment.java    From Cybernet-VPN with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected String doInBackground(String... params) {

    try
    {
        URL whatismyip = new URL("http://checkip.amazonaws.com");
        BufferedReader input = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
        ip = input.readLine();

        HttpURLConnection connection = (HttpURLConnection) new URL("http://ip-api.com/json/" + ip).openConnection();
        connection.setReadTimeout(3000);
        connection.setConnectTimeout(3000);
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpsURLConnection.HTTP_OK) {
            throw new IOException("HTTP error code: " + responseCode);
        }
        InputStream in = new java.io.BufferedInputStream(connection.getInputStream());
        //s=readStream(in,10000);
        s=convertStreamToString(in);
        jsonObject=new JSONObject(s);

        city=jsonObject.getString("city");
        isp=jsonObject.getString("org");
        state=jsonObject.getString("regionName");
        country=jsonObject.getString("country");

        Log.d("MainActivity", "Call reached here");

        if (in != null) {
            // Converts Stream to String with max length of 500.
            Log.d("MainActivity call 2", s);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return s;
}
 
Example 20
Source File: DzdpNet.java    From wasindoor with Apache License 2.0 3 votes vote down vote up
private String getHttpServerResponse(String url) throws Exception {

		URL getUrl = new URL(url);
		System.out.println(url);
		// ���ƴ�յ�URL�������ӣ�URL.openConnection()�������
		// URL�����ͣ����ز�ͬ��URLConnection����Ķ������������ǵ�URL��һ��http�������ʵ���Ϸ��ص���HttpURLConnection

		HttpURLConnection connection = (HttpURLConnection) getUrl
				.openConnection();

		// ����������������ӣ���δ�������

		connection.connect();

		// ������ݵ���������ʹ��Reader��ȡ���ص����

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), "UTF-8"));

		StringBuffer lines = new StringBuffer(9082);
		String line = "";
		while ((line = reader.readLine()) != null) {

			lines.append(line).append(System.getProperty("line.separator"));
		}

		reader.close();

		connection.disconnect();
		System.out.println(lines.toString());
		return lines.toString();

	}