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

The following examples show how to use javax.net.ssl.HttpsURLConnection#getHeaderField() . 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: 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 2
Source File: GoogleUriActivity.java    From LocationPrivacy with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected String doInBackground(Void... params) {
    String result = null;
    HttpsURLConnection connection = null;
    try {
        connection = NetCipher.getHttpsURLConnection(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
        result = connection.getHeaderField("Location");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null)
            connection.disconnect();
    }
    return result;
}
 
Example 3
Source File: MultiPart.java    From constellation with Apache License 2.0 5 votes vote down vote up
/**
     * Post this multipart message using the given connection.
     *
     * @param conn An HTTPS connection.
     *
     * @return A (message, location) pair; the message is the http response
     * message, location is null if the response code was not in the 200 range.
     *
     * @throws IOException if the thread is interrupted during the connection.
     */
    public Pair<String, String> post(final HttpsURLConnection conn) throws IOException {
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", BrandingUtilities.APPLICATION_NAME);
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundary());
        conn.setRequestProperty("Content-Length", Integer.toString(size()));

        try (final OutputStream os = conn.getOutputStream()) {
            os.write(getBuffer());
        }

        final int code = conn.getResponseCode();

        final String location;
        final int responseClass = code / 100;
        if (responseClass == 2) {
            location = conn.getHeaderField("Location");
        } else {
            location = null;
        }

//        conn.getHeaderFields().entrySet().stream().forEach(entry ->
//        {
//            System.out.printf("@@MultiPart header %s: %s\n", entry.getKey(), entry.getValue());
//        });
//        System.out.printf("@@MultiPart response [%s]\n", new String(getBody(conn, code)));
        return new Pair<>(conn.getResponseMessage(), location);
    }
 
Example 4
Source File: TestHttpCookieFlag.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpsCookie() throws IOException, GeneralSecurityException {
  URL base = new URL("https://" + NetUtils.getHostPortString(server
          .getConnectorAddress(1)));
  HttpsURLConnection conn = (HttpsURLConnection) new URL(base,
          "/echo").openConnection();
  conn.setSSLSocketFactory(clientSslFactory.createSSLSocketFactory());

  String header = conn.getHeaderField("Set-Cookie");
  List<HttpCookie> cookies = HttpCookie.parse(header);
  Assert.assertTrue(!cookies.isEmpty());
  Assert.assertTrue(header.contains("; HttpOnly"));
  Assert.assertTrue(cookies.get(0).getSecure());
  Assert.assertTrue("token".equals(cookies.get(0).getValue()));
}
 
Example 5
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 6
Source File: TestHttpCookieFlag.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpsCookie() throws IOException, GeneralSecurityException {
  URL base = new URL("https://" + NetUtils.getHostPortString(server
          .getConnectorAddress(1)));
  HttpsURLConnection conn = (HttpsURLConnection) new URL(base,
          "/echo").openConnection();
  conn.setSSLSocketFactory(clientSslFactory.createSSLSocketFactory());

  String header = conn.getHeaderField("Set-Cookie");
  List<HttpCookie> cookies = HttpCookie.parse(header);
  Assert.assertTrue(!cookies.isEmpty());
  Assert.assertTrue(header.contains("; HttpOnly"));
  Assert.assertTrue(cookies.get(0).getSecure());
  Assert.assertTrue("token".equals(cookies.get(0).getValue()));
}
 
Example 7
Source File: LinkedResponse.java    From webex-java-sdk with MIT License 5 votes vote down vote up
private void parseLinks(HttpsURLConnection connection) throws IOException {
    urls.clear();
    String link = connection.getHeaderField("Link");
    if (link != null && !"".equals(link)) {
        Matcher matcher = linkPattern.matcher(link);
        while (matcher.find()) {
            String url = matcher.group(1);
            String foundRel = matcher.group(2);
            urls.put(foundRel, new URL(url));
        }
    }
}
 
Example 8
Source File: RequestResult.java    From SaliensAuto with GNU General Public License v3.0 4 votes vote down vote up
private int getEResult(HttpsURLConnection conn) {
    String s = conn.getHeaderField("x-eresult");
    if(s==null) s = conn.getHeaderField("X-eresult");
    if(s==null) return -1;
    return Integer.valueOf(s);
}
 
Example 9
Source File: RequestResult.java    From SaliensAuto with GNU General Public License v3.0 4 votes vote down vote up
private String getErrorMessage(HttpsURLConnection conn) {
    String s = conn.getHeaderField("x-error_message");
    if(s==null) s = conn.getHeaderField("X-error_message");
    return convertErrorMessage(eResult,s);
}
 
Example 10
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;
}
 
Example 11
Source File: Client.java    From webex-java-sdk with MIT License 4 votes vote down vote up
private HttpsURLConnection getLink(HttpsURLConnection connection, String rel) throws IOException {
    String link = connection.getHeaderField("Link");
    return parseLinkHeader(link, rel);
}
 
Example 12
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;
}