Example usage for java.net HttpURLConnection getHeaderFieldKey

List of usage examples for java.net HttpURLConnection getHeaderFieldKey

Introduction

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

Prototype

public String getHeaderFieldKey(int n) 

Source Link

Document

Returns the key for the n th header field.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    URL u = new URL("http://www.java2s.com");
    HttpURLConnection uc = (HttpURLConnection) u.openConnection();
    int code = uc.getResponseCode();
    String response = uc.getResponseMessage();
    System.out.println("HTTP/1.x " + code + " " + response);
    for (int j = 1;; j++) {
        String header = uc.getHeaderField(j);
        String key = uc.getHeaderFieldKey(j);
        if (header == null || key == null)
            break;
        System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
    }//from   w ww  . j  a v  a 2s  . c o  m
    InputStream in = new BufferedInputStream(uc.getInputStream());

    Reader r = new InputStreamReader(in);
    int c;
    while ((c = r.read()) != -1) {
        System.out.print((char) c);
    }
}

From source file:Main.java

@SuppressLint("NewApi")
public static void getURL(String path) {
    String fileName = "";
    String dir = "/IndoorNavi/";
    File sdRoot = Environment.getExternalStorageDirectory();
    try {/*from   w  w  w . j  av  a2 s.c om*/
        // Open the URLConnection for reading
        URL u = new URL(path);
        // URL u = new URL("http://www.baidu.com/");
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();

        int code = uc.getResponseCode();
        String response = uc.getResponseMessage();
        //System.out.println("HTTP/1.x " + code + " " + response);
        for (int j = 1;; j++) {
            String key = uc.getHeaderFieldKey(j);
            String header = uc.getHeaderField(j);
            if (!(key == null)) {
                if (key.equals("Content-Name"))
                    fileName = header;
            }
            if (header == null || key == null)
                break;
            //System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
        }
        Log.i("zhr", fileName);
        //System.out.println();

        try (InputStream in = new BufferedInputStream(uc.getInputStream())) {

            // chain the InputStream to a Reader
            Reader r = new InputStreamReader(in);
            int c;
            File mapFile = new File(sdRoot, dir + fileName);
            mapFile.createNewFile();
            FileOutputStream filecon = new FileOutputStream(mapFile);
            while ((c = r.read()) != -1) {
                //System.out.print((char) c);
                filecon.write(c);
                filecon.flush();

            }
            filecon.close();
        }

    } catch (MalformedURLException ex) {
        System.err.println(path + " is not a parseable URL");
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

From source file:org.rapidcontext.app.plugin.http.HttpPostProcedure.java

/**
 * Logs the HTTP response to the procedure call context.
 *
 * @param cx             the procedure call context
 * @param con            the HTTP connection
 * @param data           the HTTP response data
 *
 * @throws IOException if the HTTP response couldn't be extracted
 *///ww w. jav a2  s  .  co  m
private static void logResponse(CallContext cx, HttpURLConnection con, String data) throws IOException {

    cx.log(con.getHeaderField(0));
    for (int i = 1; true; i++) {
        String key = con.getHeaderFieldKey(i);
        if (key == null) {
            break;
        }
        cx.log("  " + key + ": " + con.getHeaderField(i));
    }
    if (data != null) {
        cx.log(data);
    }
}

From source file:com.dream.library.utils.AbFileUtil.java

/**
 * ???xx.??.//  ww  w.  j a  v  a  2s . co m
 *
 * @param connection 
 * @return ??
 */
public static String getRealFileName(HttpURLConnection connection) {
    String name = null;
    try {
        if (connection == null) {
            return name;
        }
        if (connection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mime = connection.getHeaderField(i);
                if (mime == null) {
                    break;
                }
                // "Content-Disposition","attachment; filename=1.txt"
                // Content-Length
                if ("content-disposition".equals(connection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase());
                    if (m.find()) {
                        return m.group(1).replace("\"", "");
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        AbLog.e("???");
    }
    return name;
}

From source file:Main.java

public Main() {
    JPanel inputPanel = new JPanel(new BorderLayout(3, 3));
    go.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                URL pageURL = new URL("http://www.google.com");
                HttpURLConnection urlConnection = (HttpURLConnection) pageURL.openConnection();
                int respCode = urlConnection.getResponseCode();
                String response = urlConnection.getResponseMessage();
                codeArea.setText("HTTP/1.x " + respCode + " " + response + "\n");
                int count = 1;
                while (true) {
                    String header = urlConnection.getHeaderField(count);
                    String key = urlConnection.getHeaderFieldKey(count);
                    if (header == null || key == null) {
                        break;
                    }//from  w  w  w.  j a  v  a 2  s  .  com
                    codeArea.append(urlConnection.getHeaderFieldKey(count) + ": " + header + "\n");
                    count++;
                }
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                Reader r = new InputStreamReader(in);
                int c;
                while ((c = r.read()) != -1) {
                    codeArea.append(String.valueOf((char) c));
                }
                codeArea.setCaretPosition(1);
            } catch (Exception ee) {
            }
        }
    });
    inputPanel.add(BorderLayout.EAST, go);
    JScrollPane codeScroller = new JScrollPane(codeArea);
    add(BorderLayout.NORTH, inputPanel);
    add(BorderLayout.CENTER, codeScroller);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(700, 500);
    this.setVisible(true);
}

From source file:org.getobjects.appserver.core.WOHTTPConnection.java

protected static void attachToResponse(HttpURLConnection _urlConnection, WOResponse _r) {
    String httpVersion = null;/*from  w  w  w  . ja va2  s.c o  m*/
    int status = WOMessage.HTTP_STATUS_INTERNAL_ERROR;

    // retrieve status and HTTP version
    String resp = _urlConnection.getHeaderField(0);
    if (resp != null) {
        String[] fields = resp.split(" ");

        if (fields.length >= 2) {
            try {
                httpVersion = fields[0];
                status = Integer.parseInt(fields[1]);
            } catch (Exception e) {
                try {
                    status = _urlConnection.getResponseCode();
                } catch (IOException e1) {
                }
            }
        }
    }

    // apply status
    _r.setStatus(status);
    // kinda hackish
    _r.httpVersion = httpVersion;

    for (int i = 1; _urlConnection.getHeaderField(i) != null; i++) {
        String headerProp = _urlConnection.getHeaderField(i);
        String headerKey = _urlConnection.getHeaderFieldKey(i).toLowerCase();
        String[] headerValues = headerProp.split(" , ");
        if (headerValues.length == 1) {
            _r.setHeaderForKey(headerProp, headerKey);
        } else {
            List<String> header = new ArrayList<String>(headerValues.length);
            for (String value : headerValues) {
                header.add(value.trim());
            }
            _r.setHeadersForKey(header, headerKey);
        }
    }
}

From source file:org.apache.cactus.client.authentication.FormAuthentication.java

/**
 * Get a cookie required to be set by set-cookie header field.
 * @param theConnection a {@link HttpURLConnection}
 * @param theTarget the target cookie name
 * @return the {@link Cookie}/*from  w  w w .java 2s.  c o  m*/
 */
private Cookie getCookie(HttpURLConnection theConnection, String theTarget) {
    // Check (possible multiple) cookies for a target.
    int i = 1;
    String key = theConnection.getHeaderFieldKey(i);
    while (key != null) {
        if (key.equalsIgnoreCase("set-cookie")) {
            // Cookie is in the form:
            // "NAME=VALUE; expires=DATE; path=PATH;
            //  domain=DOMAIN_NAME; secure"
            // The only thing we care about is finding a cookie with
            // the name "JSESSIONID" and caching the value.
            String cookiestr = theConnection.getHeaderField(i);
            String nameValue = cookiestr.substring(0, cookiestr.indexOf(";"));
            int equalsChar = nameValue.indexOf("=");
            String name = nameValue.substring(0, equalsChar);
            String value = nameValue.substring(equalsChar + 1);
            if (name.equalsIgnoreCase(theTarget)) {
                return new Cookie(theConnection.getURL().getHost(), name, value);
            }
        }
        key = theConnection.getHeaderFieldKey(++i);
    }
    return null;
}

From source file:org.apache.axis2.transport.testkit.http.JavaNetClient.java

public void sendMessage(ClientOptions options, ContentType contentType, byte[] message) throws Exception {
    URL url = new URL(channel.getEndpointReference().getAddress());
    log.debug("Opening connection to " + url + " using " + URLConnection.class.getName());
    try {//from ww  w  .j  a  v  a  2  s  . c  o m
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", contentType.toString());
        if (contentType.getBaseType().equals("text/xml")) {
            connection.setRequestProperty("SOAPAction", "");
        }
        OutputStream out = connection.getOutputStream();
        out.write(message);
        out.close();
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            log.debug("Response code: " + httpConnection.getResponseCode());
            log.debug("Response message: " + httpConnection.getResponseMessage());
            int i = 0;
            String headerValue;
            while ((headerValue = httpConnection.getHeaderField(i)) != null) {
                String headerName = httpConnection.getHeaderFieldKey(i);
                if (headerName != null) {
                    log.debug(headerName + ": " + headerValue);
                } else {
                    log.debug(headerValue);
                }
                i++;
            }
        }
        InputStream in = connection.getInputStream();
        IOUtils.copy(in, System.out);
        in.close();
    } catch (IOException ex) {
        log.debug("Got exception", ex);
        throw ex;
    }
}

From source file:com.ris.mobile.ecloud.util.AbFileUtil.java

/**
 * ???xx.??.//from   ww w  .  j a  v  a  2 s  .c  o m
 * @param connection 
 * @return ??
 */
public static String getRealFileName(HttpURLConnection connection) {
    String name = null;
    try {
        if (connection == null) {
            return name;
        }
        if (connection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mime = connection.getHeaderField(i);
                if (mime == null) {
                    break;
                }
                // "Content-Disposition","attachment; filename=1.txt"
                // Content-Length
                if ("content-disposition".equals(connection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase());
                    if (m.find()) {
                        return m.group(1).replace("\"", "");
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        //AbLogUtil.e(AbFileUtil.class, "???");
    }
    return name;
}

From source file:com.bnrc.util.AbFileUtil.java

/**
 * ????xx.??./*from w ww.j a  va  2  s. c  o  m*/
 * @param connection ?
 * @return ??
 */
public static String getRealFileName(HttpURLConnection connection) {
    String name = null;
    try {
        if (connection == null) {
            return name;
        }
        if (connection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mime = connection.getHeaderField(i);
                if (mime == null) {
                    break;
                }
                // "Content-Disposition","attachment; filename=1.txt"
                // Content-Length
                if ("content-disposition".equals(connection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase());
                    if (m.find()) {
                        return m.group(1).replace("\"", "");
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        AbLogUtil.e(AbFileUtil.class, "??");
    }
    return name;
}