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

The following examples show how to use javax.net.ssl.HttpsURLConnection#getHeaderFields() . 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: HttpResponse.java    From jarling with MIT License 6 votes vote down vote up
public HttpResponse(HttpsURLConnection httpsURLConnection) throws StarlingBankRequestException {
    this.httpsURLConnection = httpsURLConnection;
    try {
        if (httpsURLConnection.getResponseCode() < HttpsURLConnection.HTTP_BAD_REQUEST){
            this.is = httpsURLConnection.getInputStream();
        }else {
            this.is = httpsURLConnection.getErrorStream();
            processStatusCode(httpsURLConnection);
        }
        this.statusCode = httpsURLConnection.getResponseCode();
        this.expiration = httpsURLConnection.getExpiration();
        this.request = httpsURLConnection.getURL();
        this.expiration = httpsURLConnection.getExpiration();
        this.lastModified = httpsURLConnection.getLastModified();
        this.responseHeaders = httpsURLConnection.getHeaderFields();
        this.contentType = httpsURLConnection.getContentType();
        this.contentEncoding = httpsURLConnection.getContentEncoding();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 3
Source File: RestClient.java    From constellation with Apache License 2.0 5 votes vote down vote up
/**
 * Post method which will convert the {@code params} to a JSON body. At the
 * moment this method only supports a simple JSON object. That is, it does
 * not convert arrays into JSON.
 *
 * @param url The URL to request
 * @param params A simple key/value pair in which values do not contain
 * Arrays, Sets etc
 *
 * @throws IOException
 */
public void post(final String url, final Map<String, String> params) throws IOException {
    beforePost(url, params);

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

        try (final BufferedWriter request = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8.name()))) {
            request.write(generateJsonFromFlatMap(params));
            request.flush();
        }

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

        bytes = null;
        if (Response.isCodeSuccess(responseCode)) {
            bytes = getBody(connection, responseCode);
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    afterPost(url, params);
}
 
Example 4
Source File: RestClient.java    From constellation with Apache License 2.0 5 votes vote down vote up
/**
 * Post method similar to {@code post} but has the option to supply a json
 * string that will be posted in the message body.
 *
 * @param url The URL to request
 * @param params A simple key/value pair in which values do not contain
 * Arrays, Sets etc
 * @param json The json string to be posted in the message body
 *
 * @throws IOException
 */
public void postWithJson(final String url, final Map<String, String> params, final String json) throws IOException {
    beforePost(url, params);

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

        try (final BufferedWriter request = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8.name()))) {
            request.write(json);
            request.flush();
        }

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

        bytes = null;
        if (Response.isCodeSuccess(responseCode)) {
            bytes = getBody(connection, responseCode);
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    afterPost(url, params);
}
 
Example 5
Source File: RestClient.java    From constellation with Apache License 2.0 5 votes vote down vote up
/**
 * Post method similar to {@code post} but has the option to supply a byte
 * array that will be posted in the message body.
 *
 * @param url The URL to request
 * @param params A simple key/value pair in which values do not contain
 * Arrays, Sets etc
 * @param bytes The bytes to be posted in the message body
 *
 * @throws IOException
 */
public void postWithBytes(final String url, final Map<String, String> params, final byte[] bytes) throws IOException {
    beforePost(url, params);

    HttpsURLConnection connection = null;
    try {
        connection = makePostConnection(url, params);
        try (final DataOutputStream request = new DataOutputStream(connection.getOutputStream())) {
            request.write(bytes);
            request.flush();
        }

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

        this.bytes = null;
        if (Response.isCodeSuccess(responseCode)) {
            this.bytes = getBody(connection, responseCode);
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    afterPost(url, params);
}
 
Example 6
Source File: BaseLogger.java    From gateway-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public void logResponse(HttpsURLConnection c, String data) {
    String log = "RESPONSE: ";

    // log response headers
    Map<String, List<String>> headers = c.getHeaderFields();
    Set<String> keys = headers.keySet();

    int i = 0;
    for (String key : keys) {
        List<String> values = headers.get(key);
        for (String value : values) {
            if (i == 0 && key == null) {
                log += value;

                if (data != null && data.length() > 0) {
                    log += "\n-- Data: " + data;
                }
            } else {
                log += "\n-- " + (key == null ? "" : key + ": ") + value;
            }
            i++;
        }
    }

    log += "\n-- Cipher Suite: " + c.getCipherSuite();

    String[] parts = log.split("\n");
    for (String part : parts) {
        logDebug(part);
    }
}
 
Example 7
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 8
Source File: HttpDownloader.java    From SkyTube with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Response execute(Request request) throws IOException, ReCaptchaException {
	final String httpMethod = request.httpMethod();
	final String url = request.url();
	final Map<String, List<String>> headers = request.headers();
	final Localization localization = request.localization();

	final HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();

	connection.setConnectTimeout(30 * 1000); // 30s
	connection.setReadTimeout(30 * 1000); // 30s
	connection.setRequestMethod(httpMethod);

	connection.setRequestProperty("User-Agent", USER_AGENT);
	connection.setRequestProperty("Accept-Language", "en");

	for (Map.Entry<String, List<String>> pair : headers.entrySet()) {
		final String headerName = pair.getKey();
		final List<String> headerValueList = pair.getValue();

		if (headerValueList.size() > 1) {
			connection.setRequestProperty(headerName, null);
			for (String headerValue : headerValueList) {
				connection.addRequestProperty(headerName, headerValue);
			}
		} else if (headerValueList.size() == 1) {
			connection.setRequestProperty(headerName, headerValueList.get(0));
		}
	}

	try(OutputStream outputStream = sendOutput(request, connection)) {

		final String response = readResponse(connection);

		final int responseCode = connection.getResponseCode();
		final String responseMessage = connection.getResponseMessage();
		final Map<String, List<String>> responseHeaders = connection.getHeaderFields();
		final URL latestUrl = connection.getURL();
		return new Response(responseCode, responseMessage, responseHeaders, response, latestUrl.toString());
	} catch (Exception e) {
		/*
		 * HTTP 429 == Too Many Request
		 * Receive from Youtube.com = ReCaptcha challenge request
		 * See : https://github.com/rg3/youtube-dl/issues/5138
		 */
		if (connection.getResponseCode() == 429) {
			throw new ReCaptchaException("reCaptcha Challenge requested", url);
		}

		throw new IOException(connection.getResponseCode() + " " + connection.getResponseMessage(), e);
	}
}