Java Code Examples for javax.net.ssl.HttpsURLConnection#getResponseCode()

The following examples show how to use javax.net.ssl.HttpsURLConnection#getResponseCode() . 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: RestClient.java    From constellation with Apache License 2.0 6 votes vote down vote up
/**
 * A generic "send request / read response" method.
 * <p>
 * The REST calls each return a body containing a JSON document.
 *
 * @param url The URL to request.
 * @param params Query parameters.
 *
 * @throws IOException
 */
public void get(final String url, final Map<String, String> params) throws IOException {
    beforeGet(url, params);

    HttpsURLConnection connection = null;
    try {
        connection = makeGetConnection(url, params);

        responseCode = connection.getResponseCode();
        responseMessage = connection.getResponseMessage();
        headerFields = connection.getHeaderFields();

        bytes = null;
        if (Response.isCodeSuccess(responseCode)) {
            bytes = getBody(connection, responseCode);
        }
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    afterGet(url, params);
}
 
Example 2
Source File: IntegrationTest.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testTopPage() throws Exception {
    String url = getAppBaseURL();
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestMethod("GET");

    int responseCode = con.getResponseCode();

    // It ensures that our Application Default Credentials work well.
    assertEquals(200, responseCode);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    String contents = response.toString();

    assertTrue(contents.contains(PROJECT_ID));
}
 
Example 3
Source File: IntegrationTest.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testPushHandlerIsProtected() throws Exception {
    String url = getAppBaseURL() + "_ah/push-handlers/receive_message";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    String urlParams = "p1=a";
    byte[] postData = urlParams.getBytes( StandardCharsets.UTF_8 );
    con.setInstanceFollowRedirects(false);
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    con.setRequestProperty(
            "Content-Length", Integer.toString(postData.length));
    con.setRequestProperty(
            "Content-Type", "application/x-www-form-urlencoded");
    try(DataOutputStream wr = new DataOutputStream(
            con.getOutputStream())) {
        wr.write(postData);
        wr.flush();
    }
    int responseCode = con.getResponseCode();
    assertEquals(302, responseCode);
}
 
Example 4
Source File: FlightDataSource.java    From hazelcast-jet-demos with Apache License 2.0 6 votes vote down vote up
private JsonArray pollForAircraft() throws IOException {
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    StringBuilder response = new StringBuilder();
    try {
        con.setRequestMethod("GET");
        con.addRequestProperty("User-Agent", "Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 40.0.2214.91 Safari / 537.36");
        con.addRequestProperty("api-auth", API_AUTHENTICATION_KEY);
        int responseCode = con.getResponseCode();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        }
        if (responseCode != 200) {
            logger.info("API returned error: " + responseCode + " " + response);
            return new JsonArray();
        }
    } finally {
        con.disconnect();
    }

    JsonValue value = Json.parse(response.toString());
    JsonObject object = value.asObject();
    return object.get("acList").asArray();
}
 
Example 5
Source File: HttpApiIT.java    From timely with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutMetric() throws Exception {
    final Server s = new Server(conf);
    s.run();
    try {
        Metric m = Metric.newBuilder().name("sys.cpu.user").value(TEST_TIME, 1.0D).tag(new Tag("tag1", "value1"))
                .build();
        new Metric();
        URL url = new URL("https://127.0.0.1:54322/api/put");
        HttpsURLConnection con = getUrlConnection(url);
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json");
        String requestJSON = JsonUtil.getObjectMapper().writeValueAsString(m);
        System.out.println(requestJSON);
        con.setRequestProperty("Content-Length", String.valueOf(requestJSON.length()));
        OutputStream wr = con.getOutputStream();
        wr.write(requestJSON.getBytes(UTF_8));
        int responseCode = con.getResponseCode();
        Assert.assertEquals(200, responseCode);
    } finally {
        s.shutdown();
    }
}
 
Example 6
Source File: Engine.java    From acunetix-plugin with MIT License 6 votes vote down vote up
private Resp doPostLoc(String urlStr, String urlParams) throws IOException, NullPointerException {
    HttpsURLConnection connection = openConnection(urlStr, "POST");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
        outputStream.writeBytes(urlParams);
    }
    String location = connection.getHeaderField("Location");
    Resp resp = new Resp();
    resp.respCode = connection.getResponseCode();
    try {
        resp.respStr = location.substring(location.lastIndexOf("/") + 1);
        } catch (NullPointerException e){
            e.printStackTrace();
            throw new ConnectionException();
        }
    return resp;
}
 
Example 7
Source File: ConnectUnitTests.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
@BeforeClass
public static void getAccessTokenUsingPasswordGrant() throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException {
    URL url = new URL(TOKEN_ENDPOINT);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    String urlParameters = String.format(
            "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s",
            GRANT_TYPE,
            URLEncoder.encode(Constants.MICROSOFT_GRAPH_API_ENDPOINT_RESOURCE_ID, "UTF-8"),
            clientId,
            username,
            password
    );

    connection.setRequestMethod(REQUEST_METHOD);
    connection.setRequestProperty("Content-Type", CONTENT_TYPE);
    connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length));

    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(urlParameters);
    dataOutputStream.flush();
    dataOutputStream.close();

    connection.getResponseCode();

    BufferedReader in = new BufferedReader(
            new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    JsonParser jsonParser = new JsonParser();
    JsonObject grantResponse = (JsonObject)jsonParser.parse(response.toString());
    accessToken = grantResponse.get("access_token").getAsString();
}
 
Example 8
Source File: HTTPStrictTransportSecurityIT.java    From qonduit with Apache License 2.0 5 votes vote down vote up
@Test
public void testHSTSRequestGet() throws Exception {
    String secureMe = "https://127.0.0.1:54322/secure-me";
    URL url = new URL(secureMe);
    HttpsURLConnection con = getUrlConnection(url);
    int responseCode = con.getResponseCode();
    assertEquals(404, responseCode);
    assertEquals("max-age=604800", con.getHeaderField(StrictTransportHandler.HSTS_HEADER_NAME));
}
 
Example 9
Source File: OnyxReporterWebserviceClient.java    From olat with Apache License 2.0 5 votes vote down vote up
public boolean isServiceAvailable(final String target) {

		final HostnameVerifier hv = new HostnameVerifier() {
			@Override
			public boolean verify(final String urlHostName, final SSLSession session) {
				if (urlHostName.equals(session.getPeerHost())) {
					return true;
				} else {
					return false;
				}
			}
		};
		HttpsURLConnection.setDefaultHostnameVerifier(hv);

		try {
			final URL url = new URL(target + "?wsdl");
			final HttpURLConnection con = (HttpURLConnection) url.openConnection();
			if (con instanceof HttpsURLConnection) {
				final HttpsURLConnection sslconn = (HttpsURLConnection) con;
				final SSLContext context = SSLContext.getInstance("SSL");
				context.init(SSLConfigurationModule.getKeyManagers(), SSLConfigurationModule.getTrustManagers(), new java.security.SecureRandom());
				sslconn.setSSLSocketFactory(context.getSocketFactory());
				sslconn.connect();
				if (sslconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					sslconn.disconnect();
					return true;
				}
			} else {
				con.connect();
				if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
					con.disconnect();
					return true;
				}
			}
		} catch (final Exception e) {
	private static final Logger log = LoggerHelper.getLogger();

		}
		return false;
	}
 
Example 10
Source File: UserController.java    From full-teaching with Apache License 2.0 5 votes vote down vote up
private boolean validateGoogleCaptcha(String token) throws Exception{
	String url = "https://www.google.com/recaptcha/api/siteverify";
	URL obj = new URL(url);
	HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

	//Add request header
	con.setRequestMethod("POST");

	String urlParameters  = "secret=" + this.recaptchaPrivateKey + "&response=" + token;

	//Send post request
	con.setDoOutput(true);
	DataOutputStream wr = new DataOutputStream(con.getOutputStream());
	wr.writeBytes(urlParameters);
	wr.flush();
	wr.close();

	int responseCode = con.getResponseCode();
	System.out.println("\nSending 'POST' request to URL : " + url);
	System.out.println("Response Code : " + responseCode);

	BufferedReader in = new BufferedReader(
	        new InputStreamReader(con.getInputStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();

	while ((inputLine = in.readLine()) != null) {
		response.append(inputLine);
	}
	in.close();

	//Print result
	System.out.println(response.toString());
	
	JSONParser parser = new JSONParser();
	JSONObject json = (JSONObject) parser.parse(response.toString());
	
	return (boolean) json.get("success");
}
 
Example 11
Source File: BungeeChat.java    From BungeeChat2 with GNU General Public License v3.0 5 votes vote down vote up
private String queryLatestVersion() {
  if (!Configuration.get().getBoolean("Miscellaneous.checkForUpdates")) return VERSION_STR;

  try {
    @Cleanup("disconnect")
    HttpsURLConnection con =
        (HttpsURLConnection)
            new URL("https://api.spigotmc.org/legacy/update.php?resource=" + PLUGIN_ID)
                .openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("GET");

    con.connect();

    int responseCode = con.getResponseCode();

    try (BufferedReader reader =
        new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
      if (responseCode != 200) {
        LoggerHelper.warning(
            "Invalid response! HTTP code: "
                + responseCode
                + " Content:\n"
                + reader.lines().collect(Collectors.joining("\n")));

        return errorVersion;
      }

      return Optional.ofNullable(reader.readLine()).orElse(errorVersion);
    }
  } catch (Exception ex) {
    LoggerHelper.warning("Could not fetch the latest version!", ex);

    return errorVersion;
  }
}
 
Example 12
Source File: ExternalSelfSignedResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private String doGetCipher() throws IOException {
    // this URL provides an always on example of an HTTPS URL utilizing self-signed certificate
    URL url = new URL("https://self-signed.badssl.com/");
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.getResponseCode();
    return con.getCipherSuite();
}
 
Example 13
Source File: Upgrade.java    From inlein with Eclipse Public License 1.0 5 votes vote down vote up
public static String latestVersion() throws Exception {
    URL url = new URL(latestUrl);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setInstanceFollowRedirects(false);

    if (conn.getResponseCode() != 302) {
        throw new Exception("Unable to detect latest inlein version");
    }
    String loc = conn.getHeaderField("location");
    return loc.substring(loc.lastIndexOf('/') + 1);
}
 
Example 14
Source File: HdfsProxy.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
private static boolean sendCommand(Configuration conf, String path)
    throws IOException {
  setupSslProps(conf);
  int sslPort = getSslAddr(conf).getPort();
  int err = 0;
  StringBuilder b = new StringBuilder();
  HostsFileReader hostsReader = new HostsFileReader(conf.get("hdfsproxy.hosts",
      "hdfsproxy-hosts"), "");
  Set<String> hostsList = hostsReader.getHosts();
  for (String hostname : hostsList) {
    HttpsURLConnection connection = null;
    try {
      connection = openConnection(hostname, sslPort, path);
      connection.connect();
      if (connection.getResponseCode() != HttpServletResponse.SC_OK) {
        b.append("\n\t" + hostname + ": " + connection.getResponseCode()
            + " " + connection.getResponseMessage());
        err++;
      }
    } catch (IOException e) {
      b.append("\n\t" + hostname + ": " + e.getLocalizedMessage());
      err++;
    } finally {
      if (connection != null)
        connection.disconnect();
    }
  }
  if (err > 0) {
    System.err.print("Command failed on the following "
        + err + " host" + (err==1?":":"s:") + b.toString() + "\n");
    return true;
  }
  return false;
}
 
Example 15
Source File: SendRefreshTokenAsyncTask.java    From OneNoteAPISampleAndroid with Apache License 2.0 5 votes vote down vote up
private Object[] attemptRefreshAccessToken(String refreshToken) throws Exception {
	/**
	 * A new connection to the endpoint that processes requests for refreshing the access token
	 */
	HttpsURLConnection refreshTokenConnection = (HttpsURLConnection) (new URL(MSA_TOKEN_REFRESH_URL)).openConnection();
	refreshTokenConnection.setDoOutput(true);
	refreshTokenConnection.setRequestMethod("POST");
	refreshTokenConnection.setDoInput(true);
	refreshTokenConnection.setRequestProperty("Content-Type", TOKEN_REFRESH_CONTENT_TYPE);
	refreshTokenConnection.connect();
	OutputStream refreshTokenRequestStream = null;
	try {	
		refreshTokenRequestStream = refreshTokenConnection.getOutputStream();
		String requestBody = MessageFormat.format(TOKEN_REFRESH_REQUEST_BODY, Constants.CLIENTID, TOKEN_REFRESH_REDIRECT_URL, refreshToken);
		refreshTokenRequestStream.write(requestBody.getBytes());
		refreshTokenRequestStream.flush();
	}
	finally {
		if(refreshTokenRequestStream != null) {
			refreshTokenRequestStream.close();
		}
	}
	if(refreshTokenConnection.getResponseCode() == 200) {
		return parseRefreshTokenResponse(refreshTokenConnection);
	}
	else {
		throw new Exception("The attempt to refresh the access token failed");
	}
}
 
Example 16
Source File: HTTPStrictTransportSecurityIT.java    From timely with Apache License 2.0 5 votes vote down vote up
@Test
public void testHSTSRequestGet() throws Exception {
    String secureMe = "https://127.0.0.1:54322/secure-me";
    URL url = new URL(secureMe);
    HttpsURLConnection con = getUrlConnection(url);
    int responseCode = con.getResponseCode();
    assertEquals(404, responseCode);
    assertEquals("max-age=604800", con.getHeaderField(StrictTransportHandler.HSTS_HEADER_NAME));
}
 
Example 17
Source File: Engine.java    From acunetix-plugin with MIT License 4 votes vote down vote up
public int doTestConnection(String urlStr) throws IOException {
    HttpsURLConnection connection = openConnection(urlStr);
    return connection.getResponseCode();
}
 
Example 18
Source File: Client.java    From MaterialWeCenter with Apache License 2.0 4 votes vote down vote up
private String doPost(String apiUrl, Map<String, String> params) {
    Log.d("POST REQUEST", apiUrl);
    // 建立请求内容
    StringBuilder builder = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.append(entry.getKey())
                .append("=")
                .append(URLEncoder.encode(entry.getValue()))
                .append("&");
    }
    builder.deleteCharAt(builder.length() - 1);
    byte[] data = builder.toString().getBytes();
    // 发出请求
    try {
        URL url = new URL(apiUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setConnectTimeout(Config.TIME_OUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        // 附上Cookie
        connection.setRequestProperty("Cookie", cooike);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", String.valueOf(data.length));
        // 发送请求内容
        OutputStream output = connection.getOutputStream();
        output.write(data);
        // 接收返回信息
        int response = connection.getResponseCode();
        if (response == HttpsURLConnection.HTTP_OK) {
            // 保存Cookie
            Map<String, List<String>> header = connection.getHeaderFields();
            List<String> cookies = header.get("Set-Cookie");
            if (cookies.size() == 3)
                cooike = cookies.get(2);
            // 处理返回的字符串流
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[Config.MAX_LINE_BUFFER];
            int len = 0;
            while ((len = input.read(buffer)) != -1)
                byteArrayOutputStream.write(buffer, 0, len);
            String str = new String(byteArrayOutputStream.toByteArray());
            Log.d("POST RESPONSE", str);
            return str;
        }
    } catch (IOException e) {
        return null;
    }
    return null;
}
 
Example 19
Source File: CompileRevenjNet.java    From dsl-compiler-client with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static boolean downloadFromGithub(
		final Context context,
		final String name,
		final String zip,
		final String additionalZip,
		final File target) throws ExitException {
	if (!context.contains(Download.INSTANCE)) {
		if (!context.canInteract()) {
			context.error("Download option not enabled.\n" +
					"Enable download option, change dependencies path or place " + name + " files in specified folder: " + target.getAbsolutePath());
			throw new ExitException();
		}
		final String answer = context.ask("Do you wish to download latest " + name + " version from the Internet (y/N):");
		if (!"y".equalsIgnoreCase(answer)) {
			throw new ExitException();
		}
	}
	try {
		context.show("Downloading " + name + " from GitHub...");
		final URL latest = new URL("https://github.com/ngs-doo/revenj/releases/latest");
		final HttpsURLConnection conn = (HttpsURLConnection) latest.openConnection();
		conn.setInstanceFollowRedirects(false);
		conn.setUseCaches(false);
		conn.connect();
		final String tag;
		if (conn.getResponseCode() != 302) {
			context.warning("Error downloading " + name + " from GitHub. Will continue with tag 1.5.0. Expecting redirect. Got: " + conn.getResponseCode());
			tag = "1.5.0";
		} else {
			final String redirect = conn.getHeaderField("Location");
			tag = redirect.substring(redirect.lastIndexOf('/') + 1);
		}
		final URL coreUrl = new URL("https://github.com/ngs-doo/revenj/releases/download/" + tag + "/" + zip + ".zip");
		Utils.unpackZip(context, target, coreUrl);
		if (additionalZip != null) {
			final URL zipUrl = new URL("https://github.com/ngs-doo/revenj/releases/download/" + tag + "/" + additionalZip + ".zip");
			Utils.unpackZip(context, target, zipUrl);
		}
	} catch (IOException ex) {
		context.error("Unable to download " + name + " from GitHub.");
		context.error(ex);
		return false;
	}
	return true;
}
 
Example 20
Source File: RoomParametersFetcher.java    From Yahala-Messenger with MIT License 4 votes vote down vote up
private LinkedList<PeerConnection.IceServer> requestTurnServers(String url)
        throws IOException, JSONException {
    LinkedList<PeerConnection.IceServer> turnServers =
            new LinkedList<PeerConnection.IceServer>();
    Log.d(TAG, "Request TURN from: " + url);
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }

    });
    HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
    //HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    CertificateFactory cf = null;
    SSLContext context = null;
    try {
 /* cf = CertificateFactory.getInstance("X.509");


  InputStream caInput = new BufferedInputStream( ApplicationLoader.applicationContext.getAssets().open("y2.crt"));
  Certificate ca = cf.generateCertificate(caInput);
  FileLog.e(TAG,"ca=" + ((X509Certificate) ca).getSubjectDN());//////////////

  String keyStoreType = KeyStore.getDefaultType();
  KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  keyStore.load(null, null);
  keyStore.setCertificateEntry("ca", ca);

  TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(keyStore);
  //Create an SSLContext that uses our TrustManager
  context = SSLContext.getInstance("TLS");
  context.init(null, tmf.getTrustManagers(), new java.security.SecureRandom());
  SSLSocketFactory sslFactory = context.getSocketFactory();
  */
        connection.setSSLSocketFactory(new DummySSLSocketFactory());//new MySSLSocketFactory2(keyStore));
    } catch (Exception e) {
        e.printStackTrace();
    }

    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            HostnameVerifier hv =
                    HttpsURLConnection.getDefaultHostnameVerifier();
            return true;//hv.verify("188.247.90.132", session);
        }
    };
    connection.setHostnameVerifier(hostnameVerifier);
    connection.setConnectTimeout(TURN_HTTP_TIMEOUT_MS);
    connection.setReadTimeout(TURN_HTTP_TIMEOUT_MS);
    int responseCode = connection.getResponseCode();
    if (responseCode != 200) {
        throw new IOException("Non-200 response when requesting TURN server from "
                + url + " : " + connection.getHeaderField(null));
    }
    InputStream responseStream = connection.getInputStream();
    String response = drainStream(responseStream);
    connection.disconnect();
    FileLog.d(TAG, "TURN response: " + response);
    JSONObject responseJSON = new JSONObject(response);
    String username = responseJSON.getString("username");
    String password = responseJSON.getString("password");
    JSONArray turnUris = responseJSON.getJSONArray("uris");
    for (int i = 0; i < turnUris.length(); i++) {
        String uri = turnUris.getString(i);
        turnServers.add(new PeerConnection.IceServer(uri, username, password));
    }
    return turnServers;
}