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.carbon.appmgt.sampledeployer.http.HttpHandler.java

public String doPostHttp(String backEnd, String payload, String your_session_id, String contentType)
        throws IOException {
    URL obj = new URL(backEnd);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    if (!your_session_id.equals("") && !your_session_id.equals("none")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id);
    }/*from  w ww.  j  ava  2 s  .  com*/
    con.setRequestProperty("Content-Type", contentType);
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (your_session_id.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (your_session_id.equals("appmSamlSsoTokenId")) {
            return con.getHeaderField("Set-Cookie").split(";")[0].split("=")[1];
        } else if (your_session_id.equals("header")) {
            return con.getHeaderField("Set-Cookie").split("=")[1].split(";")[0];
        } else {
            return response.toString();
        }
    }
    return null;
}

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

@Test
public void testKeepAlive() throws IOException {
    HttpURLConnection urlConn = request("/test/v1/tweets/1", HttpMethod.PUT, true);
    writeContent(urlConn, "data");
    assertEquals(200, urlConn.getResponseCode());

    assertEquals("keep-alive", urlConn.getHeaderField(HEADER_KEY_CONNECTION));
    urlConn.disconnect();/*from  w w w.  ja v  a 2s .c  o m*/
}

From source file:uk.co.jassoft.network.Network.java

public InputStream read(String httpUrl, String method, boolean cache) throws IOException {

    HttpURLConnection conn = null;
    try {/*from  w  w w .  ja va  2s . c  o m*/

        URL base, next;
        String location;

        while (true) {
            // inputing the keywords to google search engine
            URL url = new URL(httpUrl);

            //                if(cache) {
            //                    //Proxy instance, proxy ip = 10.0.0.1 with port 8080
            //                    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("cache", 3128));
            //                    // makking connection to the internet
            //                    conn = (HttpURLConnection) url.openConnection(proxy);
            //                }
            //                else {
            conn = (HttpURLConnection) url.openConnection();
            //                }

            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
            conn.setRequestMethod(method);
            conn.setRequestProperty("User-Agent",
                    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729)");
            conn.setRequestProperty("Accept-Encoding", "gzip");

            switch (conn.getResponseCode()) {
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
                location = conn.getHeaderField("Location");
                base = new URL(httpUrl);
                next = new URL(base, location); // Deal with relative URLs
                httpUrl = next.toExternalForm();
                continue;
            }

            break;
        }

        if (!conn.getContentType().startsWith("text/") || conn.getContentType().equals("text/xml")) {
            throw new IOException(String.format("Content of story is not Text. Returned content type is [%s]",
                    conn.getContentType()));
        }

        if ("gzip".equals(conn.getContentEncoding())) {
            return new GZIPInputStream(conn.getInputStream());
        }

        // getting the input stream of page html into bufferedreader
        return conn.getInputStream();
    } catch (Exception exception) {
        throw new IOException(exception);
    } finally {
        if (conn != null && conn.getErrorStream() != null) {
            conn.getErrorStream().close();
        }
    }
}

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

@Test
public void testExceptionMapper() throws Exception {
    HttpURLConnection urlConn = request("/test/v1/mappedException", HttpMethod.GET);
    assertEquals(Response.Status.NOT_FOUND.getStatusCode(), urlConn.getResponseCode());
    assertEquals(MediaType.TEXT_PLAIN, urlConn.getHeaderField(HttpHeaders.CONTENT_TYPE));
    urlConn.disconnect();//from   ww w.j  a  va  2  s  .com
}

From source file:org.nuxeo.http.blobprovider.HttpBlobProvider.java

/**
 * Sends a HEAD request to get the info without downloading the file.
 * <p>/*from   w  w w.ja  va  2s .  c om*/
 * If an error occurs, returns null.
 *
 * @param urlStr
 * @return the BlobInfo
 * @since 8.1
 */
public BlobInfo guessInfosFromURL(String urlStr) {

    BlobInfo bi = null;
    String attrLowerCase;
    try {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        addHeaders(connection, urlStr);

        connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {

            bi = new BlobInfo();

            bi.mimeType = connection.getContentType();
            // Remove possible ...;charset="something"
            int idx = bi.mimeType.indexOf(";");
            if (idx >= 0) {
                bi.mimeType = bi.mimeType.substring(0, idx);
            }

            bi.encoding = connection.getContentEncoding();
            bi.length = connection.getContentLengthLong();
            if (bi.length < 0) {
                bi.length = 0L;
            }

            String disposition = connection.getHeaderField("Content-Disposition");
            String fileName = null;
            if (disposition != null) {
                String[] attributes = disposition.split(";");

                for (String attr : attributes) {
                    attrLowerCase = attr.toLowerCase();
                    if (attrLowerCase.contains("filename=")) {
                        attr = attr.trim();
                        // Remove filename=
                        fileName = attr.substring(9);
                        idx = fileName.indexOf("\"");
                        if (idx > -1) {
                            fileName = fileName.substring(idx + 1, fileName.lastIndexOf("\""));
                        }
                        bi.filename = fileName;
                        break;

                    } else if (attrLowerCase.contains("filename*=utf-8''")) {
                        attr = attr.trim();
                        // Remove filename=
                        fileName = attr.substring(17);
                        idx = fileName.indexOf("\"");
                        if (idx > -1) {
                            fileName = fileName.substring(idx + 1, fileName.lastIndexOf("\""));
                        }
                        fileName = java.net.URLDecoder.decode(fileName, "UTF-8");
                        bi.filename = fileName;
                        break;
                    }
                }
            } else {
                // Try from the url
                idx = urlStr.lastIndexOf("/");
                if (idx > -1) {
                    fileName = urlStr.substring(idx + 1);
                    bi.filename = java.net.URLDecoder.decode(fileName, "UTF-8");
                }
            }
        }

    } catch (Exception e) { // Whatever the error, we fail. No need to be
        // granular here.
        bi = null;
    }

    return bi;
}

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

@Test
public void testHeaderResponse() throws IOException {
    HttpURLConnection urlConn = request("/test/v1/headerResponse", HttpMethod.GET);
    urlConn.addRequestProperty("name", "name1");

    assertEquals(200, urlConn.getResponseCode());
    assertEquals("name1", urlConn.getHeaderField("name"));
    urlConn.disconnect();/*w ww .  j  a  va2s.  c  o m*/
}

From source file:org.jared.synodroid.ds.server.SimpleSynoServer.java

/**
 * Send a request to the server.// w  w w. j a  v a  2 s . c o  m
 * 
 * @param uriP
 *            The part of the URI ie: /webman/doit.cgi
 * @param requestP
 *            The query in the form 'param1=foo&param2=yes'
 * @param methodP
 *            The method to send this request
 * @return A JSONObject containing the response of the server
 * @throws DSMException
 */
public JSONArray sendJSONRequestArray(String uriP, String requestP, String methodP, boolean log)
        throws Exception {
    HttpURLConnection con = null;
    OutputStreamWriter wr = null;
    BufferedReader br = null;
    StringBuffer sb = null;
    Exception last_exception = null;
    try {

        // For some reason in Gingerbread I often get a response code of -1.
        // Here I retry for a maximum of MAX_RETRY to send the request and it usually succeed at the second try...
        int retry = 0;
        int MAX_RETRY = 2;
        while (retry <= MAX_RETRY) {
            try {
                // Create the connection
                con = createConnection(uriP, requestP, methodP, log);
                // Add the parameters
                wr = new OutputStreamWriter(con.getOutputStream());
                wr.write(requestP);
                // Send the request
                wr.flush();
                wr.close();

                // Try to retrieve the session cookie
                String newCookie = con.getHeaderField("set-cookie");
                if (newCookie != null) {
                    synchronized (this) {
                        setCookie(newCookie);
                    }
                    if (DEBUG)
                        Log.v(Synodroid.DS_TAG, "Retreived cookies: " + cookies);
                }

                // Now read the reponse and build a string with it
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                // Verify is response if not -1, otherwise take reason from the header
                if (con.getResponseCode() == -1) {
                    retry++;
                    if (DEBUG)
                        Log.w(Synodroid.DS_TAG, "Response code is -1 (retry: " + retry + ")");
                } else {
                    if (DEBUG)
                        Log.d(Synodroid.DS_TAG, "Response is: " + sb.toString());
                    JSONArray respJSO = null;
                    try {
                        respJSO = new JSONArray(sb.toString());
                    } catch (JSONException je) {
                        respJSO = new JSONArray();
                    }
                    return respJSO;
                }
            } catch (EOFException e) {
                if (DEBUG)
                    Log.w(Synodroid.DS_TAG, "Caught EOFException while contacting the server, retying...");
                retry++;
                last_exception = e;
            } catch (SocketException e) {
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG, "Caught SocketException while contacting the server, stopping...");
                throw e;
            } catch (SSLHandshakeException e) {
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG,
                            "Caught SSLHandshakeException while contacting the server, stopping...");
                throw e;
            } catch (FileNotFoundException e) {
                String msg = e.getMessage();
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG,
                            "Could not find file " + msg + "\nProbably wrong DSM version, stopping...");
                throw e;
            } catch (Exception e) {
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG, "Caught exception while contacting the server, retying...", e);
                retry++;
                last_exception = e;
            } finally {
                con.disconnect();
            }

        }
        if (last_exception != null)
            throw last_exception;
        throw new GenericException();
    } finally {
        wr = null;
        br = null;
        sb = null;
        con = null;
    }
}

From source file:org.apache.hadoop.mapred.TestShuffleHandler.java

/**
 * Verify client prematurely closing a connection.
 *
 * @throws Exception exception.//from ww w  .j a va2  s .  co  m
 */
@Test(timeout = 10000)
public void testClientClosesConnection() throws Exception {
    final ArrayList<Throwable> failures = new ArrayList<Throwable>(1);
    Configuration conf = new Configuration();
    conf.setInt(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY, 0);
    ShuffleHandler shuffleHandler = new ShuffleHandler() {
        @Override
        protected Shuffle getShuffle(Configuration conf) {
            // replace the shuffle handler with one stubbed for testing
            return new Shuffle(conf) {
                @Override
                protected MapOutputInfo getMapOutputInfo(String base, String mapId, int reduce, String user)
                        throws IOException {
                    return null;
                }

                @Override
                protected void populateHeaders(List<String> mapIds, String jobId, String user, int reduce,
                        HttpRequest request, HttpResponse response, boolean keepAliveParam,
                        Map<String, MapOutputInfo> infoMap) throws IOException {
                    // Only set response headers and skip everything else
                    // send some dummy value for content-length
                    super.setResponseHeaders(response, keepAliveParam, 100);
                }

                @Override
                protected void verifyRequest(String appid, ChannelHandlerContext ctx, HttpRequest request,
                        HttpResponse response, URL requestUri) throws IOException {
                }

                @Override
                protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch, String user,
                        String mapId, int reduce, MapOutputInfo info) throws IOException {
                    // send a shuffle header and a lot of data down the channel
                    // to trigger a broken pipe
                    ShuffleHeader header = new ShuffleHeader("attempt_12345_1_m_1_0", 5678, 5678, 1);
                    DataOutputBuffer dob = new DataOutputBuffer();
                    header.write(dob);
                    ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
                    dob = new DataOutputBuffer();
                    for (int i = 0; i < 100000; ++i) {
                        header.write(dob);
                    }
                    return ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
                }

                @Override
                protected void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
                    if (failures.size() == 0) {
                        failures.add(new Error());
                        ctx.getChannel().close();
                    }
                }

                @Override
                protected void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) {
                    if (failures.size() == 0) {
                        failures.add(new Error());
                        ctx.getChannel().close();
                    }
                }
            };
        }
    };
    shuffleHandler.init(conf);
    shuffleHandler.start();

    // simulate a reducer that closes early by reading a single shuffle header
    // then closing the connection
    URL url = new URL(
            "http://127.0.0.1:" + shuffleHandler.getConfig().get(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY)
                    + "/mapOutput?job=job_12345_1&reduce=1&map=attempt_12345_1_m_1_0");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
    conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
    conn.connect();
    DataInputStream input = new DataInputStream(conn.getInputStream());
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    Assert.assertEquals("close", conn.getHeaderField(HttpHeaders.CONNECTION));
    ShuffleHeader header = new ShuffleHeader();
    header.readFields(input);
    input.close();

    shuffleHandler.stop();
    Assert.assertTrue("sendError called when client closed connection", failures.size() == 0);
}

From source file:org.openhab.binding.miele.internal.handler.MieleBridgeHandler.java

protected String post(URL url, Map<String, String> headers, String data) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            connection.addRequestProperty(entry.getKey(), entry.getValue());
        }/*from  w  w  w .  j a v a  2 s. c o m*/
    }

    connection.addRequestProperty("Accept-Encoding", "gzip");

    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.connect();

    OutputStream out = null;

    try {
        out = connection.getOutputStream();

        out.write(data.getBytes());
        out.flush();

        int statusCode = connection.getResponseCode();
        if (statusCode != HttpURLConnection.HTTP_OK) {
            logger.debug("An unexpected status code was returned: '{}'", statusCode);
        }
    } finally {
        if (out != null) {
            out.close();
        }
    }

    String responseEncoding = connection.getHeaderField("Content-Encoding");
    responseEncoding = (responseEncoding == null ? "" : responseEncoding.trim());

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    InputStream in = connection.getInputStream();
    try {
        in = connection.getInputStream();
        if ("gzip".equalsIgnoreCase(responseEncoding)) {
            in = new GZIPInputStream(in);
        }
        in = new BufferedInputStream(in);

        byte[] buff = new byte[1024];
        int n;
        while ((n = in.read(buff)) > 0) {
            bos.write(buff, 0, n);
        }
        bos.flush();
        bos.close();
    } finally {
        if (in != null) {
            in.close();
        }
    }

    return bos.toString();
}

From source file:org.openhab.binding.miele.handler.MieleBridgeHandler.java

protected String post(URL url, Map<String, String> headers, String data) throws IOException {

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            connection.addRequestProperty(entry.getKey(), entry.getValue());
        }/*from www.j av  a 2 s.  com*/
    }

    connection.addRequestProperty("Accept-Encoding", "gzip");

    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.connect();

    OutputStream out = null;

    try {
        out = connection.getOutputStream();

        out.write(data.getBytes());
        out.flush();

        int statusCode = connection.getResponseCode();
        if (statusCode != HttpURLConnection.HTTP_OK) {
            logger.error("An unexpected status code was returned : '{}'", statusCode);
        }
    } finally {
        if (out != null) {
            out.close();
        }
    }

    String responseEncoding = connection.getHeaderField("Content-Encoding");
    responseEncoding = (responseEncoding == null ? "" : responseEncoding.trim());

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    InputStream in = connection.getInputStream();
    try {
        in = connection.getInputStream();
        if ("gzip".equalsIgnoreCase(responseEncoding)) {
            in = new GZIPInputStream(in);
        }
        in = new BufferedInputStream(in);

        byte[] buff = new byte[1024];
        int n;
        while ((n = in.read(buff)) > 0) {
            bos.write(buff, 0, n);
        }
        bos.flush();
        bos.close();
    } finally {
        if (in != null) {
            in.close();
        }
    }

    return bos.toString();
}