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.bndtools.rt.repository.client.RemoteRestRepository.java

@Override
public PutResult put(InputStream inputStream, PutOptions options) throws Exception {
    URI postUri = new URI(baseUri.getScheme(), baseUri.getUserInfo(), baseUri.getHost(), baseUri.getPort(),
            baseUri.getPath() + "/bundles", null, null);

    HttpURLConnection conn = (HttpURLConnection) postUri.toURL().openConnection();
    conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM);
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);/*from w w  w .java2 s .c  o  m*/

    // Send the data
    byte[] buffer = new byte[1024];
    OutputStream postStream = conn.getOutputStream();
    try {
        while (true) {
            int bytesRead = inputStream.read(buffer, 0, 1024);
            if (bytesRead < 0)
                break;
            postStream.write(buffer, 0, bytesRead);
        }
        postStream.flush();
    } finally {
        IO.close(postStream);
    }

    // Read the response header
    int response = conn.getResponseCode();
    if (response < 200 || response >= 300)
        throw new Exception(String.format("Server returned error code %d", response));
    String location = conn.getHeaderField("Location");
    if (location == null)
        throw new Exception("Server did not return a Location header");

    PutResult result = new PutResult();
    result.artifact = new URI(location);
    result.digest = null;

    return result;
}

From source file:com.dv.Utils.DvFileUtil.java

/**
  * ????.// w  w w  . ja va2 s  .  c  om
  * @param url ?
  * @return ??
  */
public static String getRealFileNameFromUrl(String url) {
    String name = null;
    try {
        if (DvStrUtil.isEmpty(url)) {
            return name;
        }

        URL mUrl = new URL(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent", "");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mine = mHttpURLConnection.getHeaderField(i);
                if (mine == null) {
                    break;
                }
                if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                    if (m.find())
                        return m.group(1).replace("\"", "");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        DvLogUtil.e(DvFileUtil.class, "???");
    }
    return name;
}

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

public static HttpResponse doDelete(URL endpoint, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {/*from   w  w w. j  ava 2s  . c  om*/
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("DELETE");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support Delete??", 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));
            }
        }

        // 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:com.ontotext.s4.client.HttpClient.java

/**
* Make an API request and return the raw data from the response as an
* InputStream./*from   ww  w .j av a 2  s  . c o m*/
*
* @param target the URL to request (relative URLs will resolve against the {@link #getBaseUrl() base URL}).
* @param method the request method (GET, POST, DELETE, etc.)
* @param requestBody the object that should be serialized to JSON as the request body.
*          If <code>null</code> no request body is sent
* @param extraHeaders any additional HTTP headers, specified as an alternating sequence of header names and values
* @return for a successful response, the response stream, or <code>null</code> for a 201 response
* @throws HttpClientException if an exception occurs during processing,
*           or the server returns a 4xx or 5xx error response
*/
public InputStream requestForStream(String target, String method, Object requestBody, String... extraHeaders)
        throws HttpClientException {

    try {
        HttpURLConnection connection = sendRequest(target, method, requestBody, extraHeaders);
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            // successful response with no content
            return null;
        } else if (responseCode >= 400) {
            readError(connection);
            return null; // not reachable, readError always throws exception
        } else if (responseCode >= 300) {
            // 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
            InputStream stream = connection.getInputStream();
            IOUtils.copy(stream, new NullOutputStream());
            IOUtils.closeQuietly(stream);
            // follow the redirect
            return requestForStream(location, method, requestBody, extraHeaders);
        } else {
            return connection.getInputStream();
        }
    } catch (IOException e) {
        throw new HttpClientException(e);
    }
}

From source file:manchester.synbiochem.datacapture.SeekConnector.java

public URL createExperimentalAssay(User user, Study study, String description, String title) {
    try {//from ww  w .j  a  va 2s .  c  om
        MultipartFormData form = makeAssayCreateForm(user, study, title, description, JERM_EXPERIMENT);
        log.info("creating experimental assay with title " + title);
        HttpURLConnection c = connect("/assays");
        try {
            switch (postForm(c, form)) {
            case CREATED:
            case FOUND:
                /*
                 * Invalidate the assay cache; we know there's something new
                 * not in it.
                 */
                assayCacheTimestamp = null;
                URL url = new URL(seek, c.getHeaderField("Location"));
                log.info("assay created with location " + url);
                return url;
            case SERVICE_UNAVAILABLE:
                throw new ServiceUnavailableException("SEEK is not available");
            default:
                readErrorFromConnection(c, "problem in form post", "write to SEEK failed with code %d: %s");
            case OK:
                return null;
            }
        } finally {
            c.disconnect();
        }
    } catch (IOException e) {
        throw new InternalServerErrorException("HTTP error talking to SEEK", e);
    }
}

From source file:cn.org.eshow.framwork.util.AbFileUtil.java

/**
  * ????./*  w  w  w.  j  a  va2 s. co m*/
  * @param url ?
  * @return ??
  */
public static String getRealFileNameFromUrl(String url) {
    String name = null;
    try {
        if (AbStrUtil.isEmpty(url)) {
            return name;
        }

        URL mUrl = new URL(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent", "");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mine = mHttpURLConnection.getHeaderField(i);
                if (mine == null) {
                    break;
                }
                if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                    if (m.find())
                        return m.group(1).replace("\"", "");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        AbLogUtil.e(AbFileUtil.class, "???");
    }
    return name;
}

From source file:org.zend.sdklib.internal.target.ZendDevCloud.java

private String authenticate(String username, String password) throws IOException {
    URL url = new URL(baseUrl + USER_LOGIN);
    final String content = MessageFormat.format("username={0}&password={1}&Submit={2}",
            URLEncoder.encode(username, "UTF-8"), URLEncoder.encode(password, "UTF-8"));

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

    urlConn.setDoOutput(true);//ww  w  .j  a va 2s.  co  m
    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    DataOutputStream printout = new DataOutputStream(urlConn.getOutputStream());
    printout.writeBytes(content);
    printout.flush();
    printout.close();

    final int responseCode = urlConn.getResponseCode();
    if (responseCode != 302) {
        throw new IOException("Authentication error to: " + baseUrl);
    }

    String headerName;
    String cookie = null;
    for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) {
        if ("Set-Cookie".equals(headerName)) {
            cookie = urlConn.getHeaderField(i);
        }
    }

    urlConn.disconnect();
    cookie = cookie.substring(0, cookie.indexOf(";"));
    return cookie;
}

From source file:org.apache.hadoop.fs.http.client.HttpFSFileSystem.java

private FSDataOutputStream uploadData(String method, Path f, Map<String, String> params, int bufferSize,
        int expectedStatus) throws IOException {
    HttpURLConnection conn = getConnection(method, params, f, true);
    conn.setInstanceFollowRedirects(false);
    boolean exceptionAlreadyHandled = false;
    try {// w  w  w  .ja  v a2 s.  c o m
        if (conn.getResponseCode() == HTTP_TEMPORARY_REDIRECT) {
            exceptionAlreadyHandled = true;
            String location = conn.getHeaderField("Location");
            if (location != null) {
                conn = getConnection(new URL(location), method);
                conn.setRequestProperty("Content-Type", UPLOAD_CONTENT_TYPE);
                try {
                    OutputStream os = new BufferedOutputStream(conn.getOutputStream(), bufferSize);
                    return new HttpFSDataOutputStream(conn, os, expectedStatus, statistics);
                } catch (IOException ex) {
                    validateResponse(conn, expectedStatus);
                    throw ex;
                }
            } else {
                validateResponse(conn, HTTP_TEMPORARY_REDIRECT);
                throw new IOException("Missing HTTP 'Location' header for [" + conn.getURL() + "]");
            }
        } else {
            throw new IOException(MessageFormat.format("Expected HTTP status was [307], received [{0}]",
                    conn.getResponseCode()));
        }
    } catch (IOException ex) {
        if (exceptionAlreadyHandled) {
            throw ex;
        } else {
            validateResponse(conn, HTTP_TEMPORARY_REDIRECT);
            throw ex;
        }
    }
}

From source file:edu.asu.msse.dssoni.moviedescrpitionapp.JsonRPCClientViaThread.java

private String post(URL url, Map<String, String> headers, String data) throws Exception {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            connection.addRequestProperty(entry.getKey(), entry.getValue());
        }//  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();
        out.close();
        int statusCode = connection.getResponseCode();
        if (statusCode != HttpURLConnection.HTTP_OK) {
            throw new Exception("Unexpected status from post: " + 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();
        }
    }
    android.util.Log.d(this.getClass().getSimpleName(),
            "json rpc request via http returned string " + bos.toString());
    return bos.toString();
}

From source file:com.micro.utils.F.java

/**
  * ????.//from w  w  w. j  a  v a2s.  c o m
  * @param url ?
  * @return ??
  */
public static String getRealFileNameFromUrl(String url) {
    String name = null;
    try {
        if (TextUtils.isEmpty(url)) {
            return name;
        }

        URL mUrl = new URL(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent", "");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mine = mHttpURLConnection.getHeaderField(i);
                if (mine == null) {
                    break;
                }
                if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                    if (m.find())
                        return m.group(1).replace("\"", "");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        L.E("???");
    }
    return name;
}