Example usage for java.net HttpURLConnection getHeaderField

List of usage examples for java.net HttpURLConnection getHeaderField

Introduction

In this page you can find the example usage for java.net HttpURLConnection getHeaderField.

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testGzipCompressionWithGzipAccept() throws Exception {
    HttpURLConnection urlConn = request("/test/v1/gzipfile", HttpMethod.GET);
    urlConn.addRequestProperty(HttpHeaders.ACCEPT_ENCODING, "gzip");
    assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode());
    String contentEncoding = urlConn.getHeaderField(HttpHeaders.CONTENT_ENCODING);
    assertTrue("gzip".equalsIgnoreCase(contentEncoding));
    InputStream downStream = urlConn.getInputStream();
    assertTrue(IOUtils.toByteArray(downStream).length < IOUtils.toByteArray(
            Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").openStream()).length);
}

From source file:com.ontotext.s4.client.HttpClient.java

/**
* Read a response or error message from the given connection, handling any 303 redirect responses
* if <code>followRedirects</code> is true.
*//*from w  w w  .j a v a2  s  .c  o  m*/
private <T> T readResponseOrError(HttpURLConnection connection, TypeReference<T> responseType,
        boolean followRedirects) throws HttpClientException {

    InputStream stream = null;
    try {
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            // successful response with no content
            return null;
        }
        String encoding = connection.getContentEncoding();
        if ("gzip".equalsIgnoreCase(encoding)) {
            stream = new GZIPInputStream(connection.getInputStream());
        } else {
            stream = connection.getInputStream();
        }

        if (responseCode < 300 || responseCode >= 400 || !followRedirects) {
            try {
                return MAPPER.readValue(stream, responseType);
            } finally {
                stream.close();
            }
        } else {
            // redirect - all redirects we care about from the S4
            // APIs are 303. We have to follow them manually to make
            // authentication work properly.
            String location = connection.getHeaderField("Location");
            // consume body
            IOUtils.copy(stream, new NullOutputStream());
            IOUtils.closeQuietly(stream);
            // follow the redirect
            return get(location, responseType);
        }
    } catch (Exception e) {
        readError(connection);
        return null; // unreachable, as readError always throws exception
    }
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {//from   w w  w .j  a va 2  s .  c o m
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }

        OutputStream out = urlConnection.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while posting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java

/** This test is not a WebService test, but for simplicity it re-uses the created administrator certificate in order to connect to the
 * EJBCA Admin Web and verify returned security headers.
 * @throws IOException /*from   ww w.  j a v  a  2  s.  com*/
 * @throws CertificateException 
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws KeyManagementException 
 * @throws UnrecoverableKeyException 
 */
@Test
public void testAdminWebSecurityHeaders() throws UnrecoverableKeyException, KeyManagementException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    HttpURLConnection con = super.getHttpsURLConnection(
            "https://" + hostname + ":" + httpsPort + "/ejbca/adminweb/index.jsp");
    String xframe = con.getHeaderField("X-FRAME-OPTIONS");
    String csp = con.getHeaderField("content-security-policy");
    String xcsp = con.getHeaderField("x-content-security-policy");
    con.disconnect();
    assertNotNull("Admin web page should return X-FRAME-OPTIONS header", xframe);
    assertNotNull("Admin web page should return content-security-policy header", csp);
    assertNotNull("Admin web page should return x-content-security-policy header", xcsp);
    assertEquals("Admin web page should return X-FRAME-OPTIONS SAMEORIGIN", "SAMEORIGIN", xframe);
    assertEquals(
            "Admin web page should return csp default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self'; frame-src 'self'; form-action 'self'; plugin-types application/pdf; reflected-xss block",
            "default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self'; frame-src 'self'; form-action 'self'; reflected-xss block",
            csp);
    assertEquals(
            "Admin web page should return xcsp default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self'; frame-src 'self'; form-action 'self'; plugin-types application/pdf; reflected-xss block",
            "default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self'; frame-src 'self'; form-action 'self'; reflected-xss block",
            xcsp);
}

From source file:co.aikar.timings.TimingsExport.java

@Override
public void run() {
    out.put("data", toArrayMapper(history, TimingHistory::export));

    String response = null;/*www.  j  av  a 2 s  .c  o  m*/
    String timingsURL = null;
    try {
        HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection();
        con.setDoOutput(true);
        String hostName = "BrokenHost";
        try {
            hostName = InetAddress.getLocalHost().getHostName();
        } catch (Exception ignored) {
        }
        con.setRequestProperty("User-Agent", "Paper/" + Bukkit.getServerName() + "/" + hostName);
        con.setRequestMethod("POST");
        con.setInstanceFollowRedirects(false);

        OutputStream request = new GZIPOutputStream(con.getOutputStream()) {
            {
                this.def.setLevel(7);
            }
        };

        request.write(JSONValue.toJSONString(out).getBytes("UTF-8"));
        request.close();

        response = getResponse(con);

        if (con.getResponseCode() != 302) {
            listeners.sendMessage(
                    ChatColor.RED + "Upload Error: " + con.getResponseCode() + ": " + con.getResponseMessage());
            listeners.sendMessage(ChatColor.RED + "Check your logs for more information");
            if (response != null) {
                Bukkit.getLogger().log(Level.SEVERE, response);
            }
            return;
        }

        timingsURL = con.getHeaderField("Location");
        listeners.sendMessage(ChatColor.GREEN + "View Timings Report: " + timingsURL);

        if (response != null && !response.isEmpty()) {
            Bukkit.getLogger().log(Level.INFO, "Timing Response: " + response);
        }
    } catch (IOException ex) {
        listeners.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information");
        if (response != null) {
            Bukkit.getLogger().log(Level.SEVERE, response);
        }
        Bukkit.getLogger().log(Level.SEVERE, "Could not paste timings", ex);
    } finally {
        this.listeners.done(timingsURL);
    }
}

From source file:com.portfolio.data.attachment.XSLService.java

void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer)
        throws MalformedURLException, IOException {
    /// Receive answer
    InputStream in;//from w  ww  . j  ava2s .c  o m
    try {
        in = connection.getInputStream();
    } catch (Exception e) {
        System.out.println(e.toString());
        in = connection.getErrorStream();
    }

    String ref = null;
    if (referer != null) {
        int first = referer.indexOf('/', 7);
        int last = referer.lastIndexOf('/');
        ref = referer.substring(first, last);
    }

    response.setContentType(connection.getContentType());
    response.setStatus(connection.getResponseCode());
    response.setContentLength(connection.getContentLength());

    /// Transfer headers
    Map<String, List<String>> headers = connection.getHeaderFields();
    int size = headers.size();
    for (int i = 1; i < size; ++i) {
        String key = connection.getHeaderFieldKey(i);
        String value = connection.getHeaderField(i);
        //         response.setHeader(key, value);
        response.addHeader(key, value);
    }

    /// Deal with correct path with set cookie
    List<String> setValues = headers.get("Set-Cookie");
    if (setValues != null) {
        String setVal = setValues.get(0);
        int pathPlace = setVal.indexOf("Path=");
        if (pathPlace > 0) {
            setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break
            setVal = setVal + ref;

            response.setHeader("Set-Cookie", setVal);
        }
    }

    /// Write back data
    DataInputStream stream = new DataInputStream(in);
    byte[] buffer = new byte[1024];
    //       int size;
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        while ((size = stream.read(buffer, 0, buffer.length)) != -1)
            out.write(buffer, 0, size);

    } catch (Exception e) {
        System.out.println(e.toString());
        System.out.println("Writing messed up!");
    } finally {
        in.close();
        out.flush(); // close() should flush already, but Tomcat 5.5 doesn't
        out.close();
    }
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testCookieParam() throws Exception {
    String value = "wso2";

    HttpURLConnection urlConn = request("/test/v1/cookie/", HttpMethod.GET);
    urlConn.setRequestProperty("Cookie", "name=" + value);
    assertEquals(200, urlConn.getResponseCode());
    String content = getContent(urlConn);
    assertEquals(value, content);/*from ww  w .  ja va 2s . c  o  m*/
    String cookie = urlConn.getHeaderField("Set-Cookie");
    assertNotNull(cookie);
    assertEquals("test-cookie=" + value, cookie);
    urlConn.disconnect();
}

From source file:com.zaa.WeatherLoad.java

public void Load() {
    HttpURLConnection lv_connection = null;
    try {// w w w . j  a va 2 s . c o m
        City.InitCity();
        String lv_name, lv_dt, lv_encoding, lv_response;
        Set lt_keys = Cache.gv_city.keySet();
        Iterator lv_iterator = lt_keys.iterator();
        JSONArray lv_json_array, lv_json_weather;
        JSONObject lv_json, lv_json_response, lv_json_weather_row, lv_json_temp;
        City lv_city;
        CityTemp lv_city_temp;
        int lv_resp_code;
        InputStream lv_in_stream;
        Hashtable lv_city_temp_col;
        while (lv_iterator.hasNext()) {
            lv_name = lv_iterator.next().toString();
            lv_city_temp_col = (Hashtable) Cache.gv_city_temp.get(lv_name);
            lv_connection = (HttpURLConnection) new URL("http://api.openweathermap.org/data/2.5/weather?q="
                    + URLEncoder.encode(lv_name, "utf-8") + "&units=metric").openConnection();
            lv_connection.setConnectTimeout(30000);
            lv_connection.setReadTimeout(30000);
            lv_connection.setDoOutput(true);
            lv_connection.setDoInput(true);
            lv_connection.setRequestMethod("GET");
            lv_connection.setRequestProperty("Accept-Encoding", "gzip");
            lv_resp_code = lv_connection.getResponseCode();
            lv_in_stream = new BufferedInputStream(lv_connection.getInputStream(), 8192);
            lv_encoding = lv_connection.getHeaderField("Content-Encoding");
            if (lv_encoding != null && lv_encoding.equalsIgnoreCase("gzip")) {
                lv_in_stream = new GZIPInputStream(lv_in_stream);
            }
            lv_response = convertStreamToString(lv_in_stream);
            lv_json_response = new JSONObject(lv_response);
            if (lv_json_response.getString("cod").equals("200")) {
                lv_city = (City) Cache.gv_city.get(lv_name);
                lv_json = lv_json_response.getJSONObject("main");
                lv_city.SetTemp(lv_json.getString("temp"));
                lv_city.SetPressure(lv_json.getString("pressure"));
                lv_city.SetHumidity(lv_json.getString("humidity"));
                lv_json = lv_json_response.getJSONObject("wind");
                lv_city.SetWindSpeed(lv_json.getString("speed"));
                lv_json_weather = lv_json_response.getJSONArray("weather");
                if (lv_json_weather != null) {
                    lv_json_weather_row = (JSONObject) lv_json_weather.get(0);
                    lv_city.SetIcon(lv_json_weather_row.getString("icon").substring(0, 2));
                }
                lv_city.Save();
            }
            lv_connection.disconnect();
            lv_connection = (HttpURLConnection) new URL(
                    "http://api.openweathermap.org/data/2.5/forecast/daily?q="
                            + URLEncoder.encode(lv_name, "utf-8") + "&units=metric&cnt=7").openConnection();
            lv_connection.setConnectTimeout(30000);
            lv_connection.setReadTimeout(30000);
            lv_connection.setDoOutput(true);
            lv_connection.setDoInput(true);
            lv_connection.setRequestMethod("GET");
            lv_connection.setRequestProperty("Accept-Encoding", "gzip");
            lv_resp_code = lv_connection.getResponseCode();
            lv_in_stream = new BufferedInputStream(lv_connection.getInputStream(), 8192);
            lv_encoding = lv_connection.getHeaderField("Content-Encoding");
            if (lv_encoding != null && lv_encoding.equalsIgnoreCase("gzip")) {
                lv_in_stream = new GZIPInputStream(lv_in_stream);
            }
            lv_response = convertStreamToString(lv_in_stream);
            lv_json_response = new JSONObject(lv_response);
            if (lv_json_response.getString("cod").equals("200")) {
                CityTemp.DeleteCityTemp(lv_name);
                lv_json_array = lv_json_response.getJSONArray("list");
                if (lv_json_array != null) {
                    for (int i = 0; i < lv_json_array.length(); i++) {
                        lv_json = (JSONObject) lv_json_array.get(i);
                        lv_dt = lv_json.getString("dt");
                        lv_city_temp = (CityTemp) lv_city_temp_col.get(lv_dt);
                        if (lv_city_temp == null) {
                            lv_city_temp = new CityTemp(lv_name, lv_dt);
                            lv_city_temp_col.put(lv_dt, lv_city_temp);
                        }
                        lv_json_weather = lv_json.getJSONArray("weather");
                        if (lv_json_weather != null) {
                            lv_json_weather_row = (JSONObject) lv_json_weather.get(0);
                            lv_city_temp.SetIcon(lv_json_weather_row.getString("icon").substring(0, 2));
                        }
                        lv_json_temp = lv_json.getJSONObject("temp");
                        lv_city_temp.SetTempDay(lv_json_temp.getString("day"));
                        lv_city_temp.SetTempNight(lv_json_temp.getString("night"));
                        lv_city_temp.Save();
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        gv_handler.sendEmptyMessage(Weather.NO_NET);
    } finally {
        if (lv_connection != null) {
            lv_connection.disconnect();
        }
    }
    gv_handler.sendEmptyMessage(Weather.LOAD_OK);
}

From source file:de.gebatzens.sia.SiaAPI.java

public APIResponse doRequest(String url, JSONObject request) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(BuildConfig.BACKEND_SERVER + url).openConnection();

    con.setRequestProperty("User-Agent",
            "SchulinfoAPP/" + BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + " "
                    + BuildConfig.BUILD_TYPE + " Android " + Build.VERSION.RELEASE + " " + Build.PRODUCT + ")");
    con.setRequestProperty("Accept-Encoding", "gzip");
    con.setConnectTimeout(3000);/*from  ww  w  . j  ava2 s  .  c  o m*/
    con.setRequestMethod(request == null ? "GET" : "POST");
    con.setInstanceFollowRedirects(false);

    if (request != null) {
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json");
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(request.toString());
        wr.flush();
        wr.close();
    }

    if (BuildConfig.DEBUG)
        Log.d("ggvp", "connection to " + con.getURL() + " established");

    InputStream in = con.getResponseCode() != 200 ? con.getErrorStream() : con.getInputStream();
    String encoding = con.getHeaderField("Content-Encoding");
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        in = new GZIPInputStream(in);
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String response = "";
    String line = "";
    while ((line = reader.readLine()) != null)
        response += line;
    JSONObject json = null;
    try {
        json = new JSONObject(response);
        String state = json.getString("state");
        Object data = json.opt("data");
        String reason = json.optString("reason", "");

        Log.d("ggvp", "received state " + state + " " + con.getResponseCode() + " reason: " + reason);

        return new APIResponse(state.equals("succeeded") ? APIState.SUCCEEDED : APIState.FAILED, data, reason);

    } catch (JSONException e) {
        Log.e("ggvp", e.toString());
        e.printStackTrace();
        return new APIResponse(APIState.FAILED);
    }

}

From source file:com.zoffcc.applications.aagtl.FieldnotesUploader.java

public String SendPost(String httpURL, String data, String _cookie) throws IOException {
    URL url = new URL(httpURL);
    //URL url = new URL("http://zoff.cc/xx.cgi");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);/*  ww  w .java  2s  .  c  o m*/
    connection.setRequestProperty("Connection", "Keep-Alive");

    //System.out.println("C=" + _cookie);
    connection.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.10) Gecko/20071115 Firefox/2.0.0.10");
    connection.setRequestProperty("Cookie", _cookie);
    connection.connect();

    if (data != "") {
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(data);
        out.flush();
        out.close();
    }

    // Save Cookie
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()),
            HTMLDownloader.default_buffer_size);
    String headerName = null;
    //_cookies.clear();
    if (_cookie == "") {
        for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equalsIgnoreCase("Set-Cookie")) {
                String cookie = connection.getHeaderField(i);
                _cookie += cookie.substring(0, cookie.indexOf(";")) + "; ";
            }
        }
    }

    // Get HTML from Server
    String getData = "";
    String decodedString;
    while ((decodedString = in.readLine()) != null) {
        getData += decodedString + "\n";
    }
    in.close();

    return getData;
}