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

The following examples show how to use javax.net.ssl.HttpsURLConnection#setReadTimeout() . 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: MCLeaks.java    From LiquidBounce with GNU General Public License v3.0 6 votes vote down vote up
private static URLConnection preparePostRequest(final String body) {
    try {
        final HttpsURLConnection connection = (HttpsURLConnection) new URL("https://auth.mcleaks.net/v1/redeem").openConnection();
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201");
        connection.setDoOutput(true);

        final DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
        dataOutputStream.write(body.getBytes(StandardCharsets.UTF_8));
        dataOutputStream.flush();
        dataOutputStream.close();

        return connection;
    }catch(final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 2
Source File: SDKUtils.java    From accept-sdk-android with MIT License 6 votes vote down vote up
public static HttpsURLConnection getHttpsURLConnection(String urlString, String requestMethod,
    boolean doOutput) throws IOException {
  URL url = new URL(urlString);
  HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
  SSLSocketFactory socketFactory = getSSLSocketFactory();
  if (socketFactory != null) {
    urlConnection.setSSLSocketFactory(getSSLSocketFactory());
  }

  if (requestMethod != null) {
    urlConnection.setRequestMethod(requestMethod);
  }
  urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
  urlConnection.setReadTimeout(RECIEVE_DATA_TIMEOUT);
  urlConnection.setDoOutput(doOutput);
  urlConnection.setDoInput(true);
  return urlConnection;
}
 
Example 3
Source File: SimpleSessionServerRequester.java    From Cleanstone with MIT License 6 votes vote down vote up
@Async(value = "mcLoginExec")
public ListenableFuture<SessionServerResponse> request(Connection connection, LoginData loginData,
                                                       PublicKey publicKey) {
    try {
        String authHash = LoginCrypto.generateAuthHash(connection.getSharedSecret(), publicKey);
        URL url = new URL(SESSION_SERVER_URL
                + String.format("?username=%s&serverId=%s&ip=%s", loginData.getPlayerName(), authHash,
                URLEncoder.encode(connection.getAddress().getHostAddress(), "UTF-8")));
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        try (Reader reader = new InputStreamReader(con.getInputStream(), Charsets.UTF_8)) {
            Gson gson = new Gson();
            return new AsyncResult<>(gson.fromJson(reader, SessionServerResponse.class));
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to contact session servers", e);
    }
}
 
Example 4
Source File: HttpTransportImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private HttpsURLConnection getConnection(String request, int connectTimeout, int readTimeout) throws IOException {
    String correctedRequest = request;
    if (StringUtils.isNotBlank(correctedRequest)) {
        correctedRequest = fixRequest(correctedRequest);
        URL url = new URL(this.uri + correctedRequest);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        if (connection != null) {
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(readTimeout);
            if (sslSocketFactory != null) {
                connection.setSSLSocketFactory(sslSocketFactory);
            }
            if (hostnameVerifier != null) {
                connection.setHostnameVerifier(hostnameVerifier);
            }
        }
        return connection;
    }
    return null;
}
 
Example 5
Source File: JUnit5HttpsApiTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Response get() throws Exception {
    final URL url = new URL("https://foo.bar.not.existing.talend.com/component/test?api=true");
    final HttpsURLConnection connection = HttpsURLConnection.class.cast(url.openConnection());
    connection.setSSLSocketFactory(handler.getSslContext().getSocketFactory());
    connection.setConnectTimeout(300000);
    connection.setReadTimeout(20000);
    connection.connect();
    final int responseCode = connection.getResponseCode();
    try {
        final Map<String, String> headers = connection
                .getHeaderFields()
                .entrySet()
                .stream()
                .filter(e -> e.getKey() != null)
                .collect(toMap(Map.Entry::getKey, e -> e.getValue().stream().collect(joining(","))));
        return new ResponseImpl(headers, responseCode, IO.readBytes(connection.getInputStream()));
    } finally {
        connection.disconnect();
    }
}
 
Example 6
Source File: FlashRetreiver.java    From LibreNews-Android with GNU General Public License v3.0 5 votes vote down vote up
private boolean retreiveFlashesNonAsync(Context context) throws IOException, JSONException, ParseException{
    if (!serverLocation.getProtocol().equals("https")) {
        throw new SecurityException("Flashes may only be retrieved over a secure HTTPS connection!");
    }
    sendDebugNotification("Retrieving flashes from " + serverLocation, context);
    HttpsURLConnection urlConnection = (HttpsURLConnection) serverLocation.openConnection();
    urlConnection.setRequestProperty("Content-Type", "application/json");
    urlConnection.setRequestMethod("GET");
    urlConnection.setReadTimeout(150000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.connect();
    if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                urlConnection.getInputStream()), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        String data = sb.toString();
        JSONObject jsonData = new JSONObject(data);
        serverName = jsonData.getString("server");
        flashes = convertJsonToFlashes(jsonData.getJSONArray("latest"));
    }
    sendDebugNotification("Flashes found: " + flashes.length, context);
    return true;
}
 
Example 7
Source File: HttpKit.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = {new MyX509TrustManager()};
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new SecureRandom());

    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    http.setHostnameVerifier(new TrustAnyHostnameVerifier());

    http.setConnectTimeout(25000);

    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

    if ((headers != null) && (!headers.isEmpty())) {
        for (Entry entry : headers.entrySet()) {
            http.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}
 
Example 8
Source File: SDSageSession.java    From sagetv with Apache License 2.0 5 votes vote down vote up
private InputStreamReader delete(URL url, boolean retry) throws IOException, SDException
{
  if (SDSession.debugEnabled())
  {
    SDSession.writeDebugLine("DELETE " + url.toString());
  }

  // Verified javax.net.ssl.HttpsURLConnection is present in OpenJDK 7+.
  HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
  connection.setRequestMethod("DELETE");
  connection.setConnectTimeout(TIMEOUT);
  connection.setReadTimeout(TIMEOUT);
  connection.setRequestProperty("User-Agent", USER_AGENT);
  connection.setRequestProperty("Accept", "application/json");
  connection.setRequestProperty("Accept-Encoding", "deflate,gzip");
  connection.setRequestProperty("Accept-Charset", "ISO-8859-1");
  if (token != null)
    connection.setRequestProperty("token", token);

  // Schedules Direct will return an http error 403 if the token has expired. The token can expire
  // because another program is using the same account, so we try once to get the token back.
  if (retry && connection.getResponseCode() == 403)
  {
    token = null;
    authenticate();
    return delete(url, false);
  }

  try
  {
    // We can timeout just getting the InputStream.
    return SDUtils.getStream(connection);
  }
  catch (java.net.SocketTimeoutException e)
  {
    throw new SDException(SDErrors.SAGETV_COMMUNICATION_ERROR);
  }
}
 
Example 9
Source File: HttpsClientRequest.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
private static HttpsURLConnection getURLConnection(String requestUrl, String serverHome)
        throws IOException {
    setSSlSystemProperties(serverHome);
    URL url = new URL(requestUrl);

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setReadTimeout(30000);
    conn.setConnectTimeout(15000);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    return conn;
}
 
Example 10
Source File: IPInfo.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private static Organization getOrganization(InetAddress address) throws IOException {
    synchronized (addressOrganization) {
        if (addressOrganization.containsKey(address))
            return addressOrganization.get(address);
    }

    // https://ipinfo.io/developers
    URL url = new URL("https://ipinfo.io/" + address.getHostAddress() + "/org");
    Log.i("GET " + url);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setReadTimeout(FETCH_TIMEOUT);
    connection.connect();

    Organization organization = new Organization();
    try {
        String response = Helper.readStream(connection.getInputStream(), StandardCharsets.UTF_8.name());
        organization.name = response.trim();
        if ("".equals(organization.name) || "undefined".equals(organization.name))
            organization.name = null;
    } finally {
        connection.disconnect();
    }

    synchronized (addressOrganization) {
        addressOrganization.put(address, organization);
    }

    return organization;
}
 
Example 11
Source File: SfmtaApiCaller.java    From core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command.
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
	try {
		// Create the connection
		URL url = new URL(baseUrl);
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

		// Set parameters for the connection
		con.setRequestMethod("POST"); 
		con.setRequestProperty("content-type", "application/json");
		con.setDoOutput(true);
		con.setDoInput(true);
		con.setUseCaches (false);
		
		// API now uses basic authentication
		String authString = login.getValue() + ":" + password.getValue();
		byte[] authEncBytes =
				Base64.encodeBase64(authString.getBytes());
		String authStringEnc = new String(authEncBytes);
		con.setRequestProperty("Authorization", "Basic "
				+ authStringEnc);

		// Set the timeout so don't wait forever (unless timeout is set to 0)
		int timeoutMsec = timeout.getValue();
		con.setConnectTimeout(timeoutMsec);
		con.setReadTimeout(timeoutMsec);

		// Write the json data to the connection
		DataOutputStream wr = new DataOutputStream(con.getOutputStream ());
		wr.writeBytes(jsonStr);
		wr.flush();
		wr.close();
		
		// Get the response
		int responseCode = con.getResponseCode();
		
		// If wasn't successful then log the response so can debug
		if (responseCode != 200) {			
			String responseStr = "";
			if (responseCode != 500) {
				// Response code indicates there was a problem so get the
				// reply in case API returned useful error message
				InputStream inputStream = con.getErrorStream();
				if (inputStream != null) {
					BufferedReader in =
							new BufferedReader(new InputStreamReader(
									inputStream));
					String inputLine;
					StringBuffer response = new StringBuffer();
					while ((inputLine = in.readLine()) != null) {
						response.append(inputLine);
					}
					in.close();
					responseStr = response.toString();
				}
			}

			// Lot that response code indicates there was a problem
			logger.error("Bad HTTP response {} when writing data to SFMTA "
					+ "API. Response text=\"{}\" URL={} json=\n{}",
					responseCode, responseStr, baseUrl, jsonStr);
		}

		// Done so disconnect just for the heck of it
		con.disconnect();
		
		// Return whether was successful
		return responseCode == 200;
	} catch (IOException e) {
		logger.error("Exception when writing data to SFMTA API: \"{}\" "
				+ "URL={} json=\n{}", 
				e.getMessage(), baseUrl, jsonStr);
		
		// Return that was unsuccessful
		return false;
	}
	
}
 
Example 12
Source File: GoogleElevationApi.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
public static void getElevation(Location location, Context context) throws IOException, JSONException {
    // https://developers.google.com/maps/documentation/elevation/
    URL url = new URL("https://maps.googleapis.com/maps/api/elevation/json?locations=" +
            String.valueOf(location.getLatitude()) + "," +
            String.valueOf(location.getLongitude()) +
            "&key=AIzaSyAp0gtiT6AqaSUSlqwXSyoFCA6SCzMyr6w");
    Log.d(TAG, "url=" + url);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();

    urlConnection.setConnectTimeout(cTimeOutMs);
    urlConnection.setReadTimeout(cTimeOutMs);
    urlConnection.setRequestProperty("Accept", "application/json");

    // Set request type
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(false);
    urlConnection.setDoInput(true);

    try {
        // Check for errors
        int code = urlConnection.getResponseCode();
        if (code != HttpsURLConnection.HTTP_OK)
            throw new IOException("HTTP error " + urlConnection.getResponseCode());

        // Get response
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder json = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null)
            json.append(line);
        Log.d(TAG, json.toString());

        // Decode result
        JSONObject jroot = new JSONObject(json.toString());
        String status = jroot.getString("status");
        if ("OK".equals(status)) {
            JSONArray results = jroot.getJSONArray("results");
            if (results.length() > 0) {
                double elevation = results.getJSONObject(0).getDouble("elevation");
                location.setAltitude(elevation);
                Log.i(TAG, "Elevation " + location);
            } else
                throw new IOException("JSON no results");
        } else
            throw new IOException("JSON status " + status);
    } finally {
        urlConnection.disconnect();
    }
}
 
Example 13
Source File: UpdatesChecker.java    From ns-usbloader with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected List<String> call() {
    String respondedJson;
    try {
        URL gitHubUrl = new URL("https://api.github.com/repos/developersu/ns-usbloader/releases/latest");
        HttpsURLConnection connection = (HttpsURLConnection) gitHubUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/vnd.github.v3+json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        int status = connection.getResponseCode();
        if (status != 200) {
            return null;
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        respondedJson = br.readLine();
        br.close();
        connection.disconnect();

        if (respondedJson == null)
            return null;
    }
    catch (IOException mue){
        return null;
    }

    String newVersion = respondedJson.replaceAll("(^.*\"tag_name\":\")(.?|.+?)(\".+$)", "$2");
    String changeLog = respondedJson.replaceAll("(^.*\"body\":\")(.?|.+?)(\".+$)", "$2")
            .replaceAll("\\\\r\\\\n","\n")
            .replaceAll("#+?\\s", "");      // replace #### dsds | # dsds

    if (newVersion.matches("^v(([0-9])+?\\.)+[0-9]+(-.+)$"))                // if new version have postfix like v0.1-Experimental
        newVersion = newVersion.replaceAll("(-.*$)", "");       // cut postfix

    if ( ! newVersion.matches("^v(([0-9])+?\\.)+[0-9]+$")) {                    // check if new version structure valid
        return null;
    }

    String currentVersion;
    if (NSLMain.appVersion.matches("^v(([0-9])+?\\.)+[0-9]+(-.+)$"))        // if current version have postfix like v0.1-Experimental
        currentVersion = NSLMain.appVersion.replaceAll("(-.*$)", "");       // cut postfix
    else
        currentVersion = NSLMain.appVersion;

    List<String> returningValue = new ArrayList<>();
    if (!newVersion.equals(currentVersion)) {                     //  if latest noted version in GitHub is different to this version
        returningValue.add(newVersion);
        returningValue.add(changeLog);
        return returningValue;
    }
    returningValue.add("");
    returningValue.add("");
    return returningValue;
}
 
Example 14
Source File: RequestUtils.java    From ibm-wearables-android-sdk with Apache License 2.0 4 votes vote down vote up
public static void executeTrainRequest(String name, String uuid, List<AccelerometerData> accelerometerData, List<GyroscopeData> gyroscopeData, RequestResult requestResult) throws IOException {

        URL url = new URL("https://medge.mybluemix.net/alg/train");

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        conn.setDoInput(true);
        conn.setDoOutput(true);

        JSONObject jsonToSend = createTrainBodyJSON(name,uuid,accelerometerData,gyroscopeData);


        OutputStream outputStream = conn.getOutputStream();
        DataOutputStream wr = new DataOutputStream(outputStream);
        wr.writeBytes(jsonToSend.toString());
        wr.flush();
        wr.close();

        outputStream.close();

        String response = "";

        int responseCode=conn.getResponseCode();

        //Log.e("BBB2","" + responseCode);

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
        }
        else {
            response="{}";
        }

        handleResponse(response,requestResult);
    }
 
Example 15
Source File: DownloadTask.java    From remixed-dungeon with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    boolean result = false;

    m_listener.DownloadProgress(m_url, 0);

    try {
        URL url = new URL(m_url);
        File file = new File(m_downloadTo);

        HttpsURLConnection ucon = NetCipher.getCompatibleHttpsURLConnection(url);

        ucon.setSSLSocketFactory(new TlsOnlySocketFactory());

        ucon.setReadTimeout(2500);
        ucon.setInstanceFollowRedirects(true);
        ucon.connect();

        int repCode = ucon.getResponseCode();

        if (repCode == HttpURLConnection.HTTP_OK) {
            int bytesTotal = ucon.getContentLength();

            GLog.debug("bytes in file: " + bytesTotal);

            InputStream is = ucon.getInputStream();

            FileOutputStream fos = new FileOutputStream(file);

            byte[] buffer = new byte[16384];
            int count;
            int bytesDownloaded = 0;
            while ((count = is.read(buffer)) != -1) {
                fos.write(buffer, 0, count);
                bytesDownloaded += count;
                m_listener.DownloadProgress(m_url, bytesDownloaded);
            }

            fos.close();

            result = true;
        }

    } catch (Exception e) {
        EventCollector.logException(new ModError("Downloading",e));
    }

     m_listener.DownloadComplete(m_url, result);
}
 
Example 16
Source File: EvepraisalGetter.java    From jeveassets with GNU General Public License v2.0 4 votes vote down vote up
public static String post(Map<Item, Long> itemCounts) {
	DecimalFormat number  = new DecimalFormat("0");
	StringBuilder builder = new StringBuilder();
	for (Map.Entry<Item, Long> entry : itemCounts.entrySet()) {
		builder.append(entry.getKey().getTypeName());
		builder.append(" ");
		builder.append(number.format(entry.getValue()));
		builder.append("\r\n");
	}
	StringBuilder urlParameters = new StringBuilder();
	//market=jita&raw_textarea=avatar&persist=no
	urlParameters.append("market=");
	urlParameters.append(encode("jita"));
	urlParameters.append("&raw_textarea=");
	urlParameters.append(encode(builder.toString()));
	try {
		URL obj = new URL("https://evepraisal.com/appraisal.json");
		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

		// add request header
		con.setRequestMethod("POST");
		con.setConnectTimeout(10000);
		con.setReadTimeout(10000);

		// Send post request
		con.setDoOutput(true);
		try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
			wr.writeBytes(urlParameters.toString());
			wr.flush();
		}

		StringBuilder response;
		try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
			String inputLine;
			response = new StringBuilder();
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
		}
		// read json
		Gson gson = new GsonBuilder().create();
		Result result = gson.fromJson(response.toString(), Result.class);
		return result.getID();
		// set data
	} catch (IOException | JsonParseException ex) {
		LOG.error(ex.getMessage(), ex);
	}
	return null;
}
 
Example 17
Source File: ITestHandleHttpRequest.java    From nifi with Apache License 2.0 4 votes vote down vote up
private void secureTest(boolean twoWaySsl) throws Exception {
    CountDownLatch serverReady = new CountDownLatch(1);
    CountDownLatch requestSent = new CountDownLatch(1);

    processor = createProcessor(serverReady, requestSent);
    final TestRunner runner = TestRunners.newTestRunner(processor);
    runner.setProperty(HandleHttpRequest.PORT, "0");

    final MockHttpContextMap contextMap = new MockHttpContextMap();
    runner.addControllerService("http-context-map", contextMap);
    runner.enableControllerService(contextMap);
    runner.setProperty(HandleHttpRequest.HTTP_CONTEXT_MAP, "http-context-map");

    final Map<String, String> sslProperties = getServerKeystoreProperties();
    sslProperties.putAll(getTruststoreProperties());
    sslProperties.put(StandardSSLContextService.SSL_ALGORITHM.getName(), CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
    useSSLContextService(runner, sslProperties, twoWaySsl ? SslContextFactory.ClientAuth.REQUIRED : SslContextFactory.ClientAuth.NONE);

    final Thread httpThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                serverReady.await();

                final int port = ((HandleHttpRequest) runner.getProcessor()).getPort();
                final HttpsURLConnection connection = (HttpsURLConnection) new URL("https://localhost:"
                        + port + "/my/path?query=true&value1=value1&value2=&value3&value4=apple=orange").openConnection();

                SSLContext clientSslContext;
                if (twoWaySsl) {
                    // Use a client certificate, do not reuse the server's keystore
                    clientSslContext = SslContextFactory.createSslContext(clientTlsConfiguration);
                } else {
                    // With one-way SSL, the client still needs a truststore
                    clientSslContext = SslContextFactory.createSslContext(trustOnlyTlsConfiguration);
                }
                connection.setSSLSocketFactory(clientSslContext.getSocketFactory());
                connection.setDoOutput(false);
                connection.setRequestMethod("GET");
                connection.setRequestProperty("header1", "value1");
                connection.setRequestProperty("header2", "");
                connection.setRequestProperty("header3", "apple=orange");
                connection.setConnectTimeout(3000);
                connection.setReadTimeout(3000);

                sendRequest(connection, requestSent);
            } catch (final Throwable t) {
                // Do nothing as HandleHttpRequest doesn't respond normally
            }
        }
    });

    httpThread.start();
    runner.run(1, false, false);

    runner.assertAllFlowFilesTransferred(HandleHttpRequest.REL_SUCCESS, 1);
    assertEquals(1, contextMap.size());

    final MockFlowFile mff = runner.getFlowFilesForRelationship(HandleHttpRequest.REL_SUCCESS).get(0);
    mff.assertAttributeEquals("http.query.param.query", "true");
    mff.assertAttributeEquals("http.query.param.value1", "value1");
    mff.assertAttributeEquals("http.query.param.value2", "");
    mff.assertAttributeEquals("http.query.param.value3", "");
    mff.assertAttributeEquals("http.query.param.value4", "apple=orange");
    mff.assertAttributeEquals("http.headers.header1", "value1");
    mff.assertAttributeEquals("http.headers.header3", "apple=orange");
    mff.assertAttributeEquals("http.protocol", "HTTP/1.1");
}
 
Example 18
Source File: HttpPOSTRequest.java    From main with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected String doInBackground(String... params){

    String stringUrl = params[0];
    String firstName = params[1];
    String lastName = params[2];
    String email = params[3];
    String password = params[4];
    int yearOfBirth = Integer.parseInt(params[5]);


    JSONObject myjson = new JSONObject();

    try {

        myjson.put("user_first_name", firstName);
        myjson.put("user_last_name", lastName);
        myjson.put("user_email", email);
        myjson.put("user_password", password);
        myjson.put("user_year_birth", yearOfBirth);

        URL url = new URL(stringUrl+getPostDataString(myjson));
        HttpsURLConnection connection =(HttpsURLConnection) url.openConnection();

        connection.setRequestMethod(REQUEST_METHOD);
        connection.setReadTimeout(READ_TIMEOUT);
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);
        connection.setDoInput(true);

        String body = myjson.toString();
        OutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
        writer.write(body);
        writer.flush();
        writer.close();
        outputStream.close();

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

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

        connection.disconnect();
        return response.toString();
    }

    catch(Exception e) {
        return "Exception: " + e.getMessage();
    }
}
 
Example 19
Source File: HttpTLSClient.java    From athenz with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    
    // parse our command line to retrieve required input
    
    CommandLine cmd = parseCommandLine(args);

    final String url = cmd.getOptionValue("url");
    final String keyPath = cmd.getOptionValue("key");
    final String certPath = cmd.getOptionValue("cert");
    final String trustStorePath = cmd.getOptionValue("trustStorePath");
    final String trustStorePassword = cmd.getOptionValue("trustStorePassword");

    // we are going to setup our service private key and
    // certificate into a ssl context that we can use with
    // our http client
    
    try {
        KeyRefresher keyRefresher = Utils.generateKeyRefresher(trustStorePath, trustStorePassword,
                certPath, keyPath);
        keyRefresher.startup();
        SSLContext sslContext = Utils.buildSSLContext(keyRefresher.getKeyManagerProxy(),
                keyRefresher.getTrustManagerProxy());
        
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
        con.setReadTimeout(15000);
        con.setDoOutput(true);
        con.connect();
        
        try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
              sb.append(line);
            }
            System.out.println("Data output: " + sb.toString());
        }

    } catch (Exception ex) {
        System.out.println("Exception: " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
}
 
Example 20
Source File: NamespaceOverrideMapper.java    From hawkular-metrics with Apache License 2.0 4 votes vote down vote up
private Map<String,String> getNamespaceMapping(Set<String> tenants) {
    Map<String,String> namespaceMap = new HashMap<>();

    if (tenants == null || tenants.isEmpty()) {
        return namespaceMap;
    }

    try {
        String path = "api/v1/namespaces";
        URL url = new URL(NamespaceHandler.KUBERNETES_MASTER_URL + "/" + path);

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + token);

        // set to 0 which indicated an infinite timeout
        connection.setConnectTimeout(0);
        connection.setReadTimeout(0);

        connection.connect();
        int responseCode = connection.getResponseCode();

        if (responseCode == 200) {

            JsonFactory jsonFactory = new JsonFactory();
            jsonFactory.setCodec(new ObjectMapper());

            InputStream inputStream = connection.getInputStream();
            JsonParser jsonParser = jsonFactory.createParser(inputStream);

            JsonNode jsonNode = jsonParser.readValueAsTree();
            // When the connection is closed, the response is null
            if (jsonNode != null) {
                JsonNode items = jsonNode.get("items");
                if (items != null && items.isArray()) {
                    for (JsonNode project : items) {
                        JsonNode metaData = project.get("metadata");
                        String projectName = metaData.get("name").asText();
                        String projectID = metaData.get("uid").asText();

                        if (tenants.contains(projectName)) {
                            namespaceMap.put(projectID, projectName);
                        }
                    }
                }
            }

            jsonParser.close();
            inputStream.close();

        } else {
            log.error("Error getting metadata from the OpenShift Master (" + responseCode + "). This may mean the 'hawkular' user does not have permission to watch projects. Waiting 2 seconds and will try again.");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }


    } catch (IOException e) {
        log.error(e);
    }

    return namespaceMap;
}