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:com.epam.catgenome.manager.externaldb.HttpDataManager.java

private String getResultFromURL(final String location) throws ExternalDbUnavailableException {

    HttpURLConnection conn = null;
    try {//from  ww w. j  ava 2 s . c om
        conn = createConnection(location);
        HttpURLConnection.setFollowRedirects(true);
        conn.setDoInput(true);
        conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON);
        conn.connect();

        int status = conn.getResponseCode();

        while (true) {
            long wait = 0;
            String header = conn.getHeaderField(HTTP_HEADER_RETRY_AFTER);

            if (header != null) {
                wait = Integer.valueOf(header);
            }

            if (wait == 0) {
                break;
            }

            LOGGER.info(String.format(WAITING_FORMAT, wait));
            conn.disconnect();

            Thread.sleep(wait * MILLIS_IN_SECOND);

            conn = (HttpURLConnection) new URL(location).openConnection();
            conn.setDoInput(true);
            conn.connect();
            status = conn.getResponseCode();

        }
        return getHttpResult(status, location, conn);
    } catch (InterruptedException | IOException e) {
        throw new ExternalDbUnavailableException(String.format(EXCEPTION_MESSAGE, location), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }

        resetProxy();
    }
}

From source file:org.apache.oozie.client.OozieClient.java

static void handleError(HttpURLConnection conn) throws IOException, OozieClientException {
    int status = conn.getResponseCode();
    String error = conn.getHeaderField(RestConstants.OOZIE_ERROR_CODE);
    String message = conn.getHeaderField(RestConstants.OOZIE_ERROR_MESSAGE);

    if (error == null) {
        error = "HTTP error code: " + status;
    }//from  w w  w  .  j  av  a 2s  . c  om

    if (message == null) {
        message = conn.getResponseMessage();
    }
    throw new OozieClientException(error, message);
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java

protected void disconnect(HttpURLConnection conn) {
    if (conn != null) {
        String connection = conn.getHeaderField(HTTPConstants.HEADER_CONNECTION);
        String protocol = conn.getHeaderField(0);
        if ((connection == null && (protocol == null || !protocol.startsWith(HTTPConstants.HTTP_1_1)))
                || (connection != null && connection.equalsIgnoreCase(HTTPConstants.CONNECTION_CLOSE))) {
            conn.disconnect();/*  w  w w . j a va  2s.c  o m*/
        } // TODO ? perhaps note connection so it can be disconnected at end of test?
    }
}

From source file:org.apache.hadoop.hdfs.ByteRangeInputStream.java

@VisibleForTesting
protected InputStream openInputStream() throws IOException {
    // Use the original url if no resolved url exists, eg. if
    // it's the first time a request is made.
    final boolean resolved = resolvedURL.getURL() != null;
    final URLOpener opener = resolved ? resolvedURL : originalURL;

    final HttpURLConnection connection = opener.connect(startPos, resolved);
    resolvedURL.setURL(getResolvedUrl(connection));

    InputStream in = connection.getInputStream();
    final Map<String, List<String>> headers = connection.getHeaderFields();
    if (isChunkedTransferEncoding(headers)) {
        // file length is not known
        fileLength = null;/*from w ww  .jav a2 s .c o m*/
    } else {
        // for non-chunked transfer-encoding, get content-length
        final String cl = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH);
        if (cl == null) {
            throw new IOException(HttpHeaders.CONTENT_LENGTH + " is missing: " + headers);
        }
        final long streamlength = Long.parseLong(cl);
        fileLength = startPos + streamlength;

        // Java has a bug with >2GB request streams.  It won't bounds check
        // the reads so the transfer blocks until the server times out
        in = new BoundedInputStream(in, streamlength);
    }

    return in;
}

From source file:com.mingsoft.weixin.util.UploadDownUtils.java

/**
 * ? // w w  w  .  j  a  v  a  2s .  c  o m
 * 
 * @return
 */
public String downMedia(String msgType, String media_id, String path) {
    String localFile = null;
    //      SimpleDateFormat df = new SimpleDateFormat("/yyyyMM/");
    try {
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + getAccessToken()
                + "&media_id=" + media_id;
        // log.error(path);
        // ? ?
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        String xx = conn.getHeaderField("Content-disposition");
        try {
            log.debug("===? +==?==" + xx);
            if (xx == null) {
                InputStream in = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String line = null;
                String result = null;
                while ((line = reader.readLine()) != null) {
                    if (result == null) {
                        result = line;
                    } else {
                        result += line;
                    }
                }
                System.out.println(result);
                JSONObject dataJson = JSONObject.parseObject(result);
                return dataJson.getString("errcode");
            }
        } catch (Exception e) {
        }
        if (conn.getResponseCode() == 200) {
            String Content_disposition = conn.getHeaderField("Content-disposition");
            InputStream inputStream = conn.getInputStream();
            // // ?
            // Long fileSize = conn.getContentLengthLong();
            //  +
            String savePath = path + "/" + msgType;
            // ??
            String fileName = StringUtil.getDateSimpleStr()
                    + Content_disposition.substring(Content_disposition.lastIndexOf(".")).replace("\"", "");
            // 
            File saveDirFile = new File(savePath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
            // ??
            if (!saveDirFile.canWrite()) {
                log.error("??");
                throw new Exception();
            }
            // System.out.println("------------------------------------------------");
            // ?
            File file = new File(saveDirFile + "/" + fileName);
            FileOutputStream outStream = new FileOutputStream(file);
            int len = -1;
            byte[] b = new byte[1024];
            while ((len = inputStream.read(b)) != -1) {
                outStream.write(b, 0, len);
            }
            outStream.flush();
            outStream.close();
            inputStream.close();
            // ?
            localFile = fileName;
        }
    } catch (Exception e) {
        log.error("? !", e);
    } finally {

    }
    return localFile;
}

From source file:org.eurekastreams.server.service.actions.strategies.links.ConnectionFacade.java

/**
 * Get the final URL after redirect.// w  w w. ja  v  a 2 s.com
 *
 * @param url
 *            the initial url.
 * @param inAccountId
 *            account id of the user making the request.
 * @return the final url.
 * @throws IOException
 *             shouldn't happen.
 */
public String getFinalUrl(final String url, final String inAccountId) throws IOException {
    HttpURLConnection connection = getConnection(url, inAccountId);
    if (connection != null && redirectCodes.contains(connection.getResponseCode())) {
        String redirUrl = connection.getHeaderField("Location");
        log.trace("Found redirect header to: " + redirUrl);

        // Check for protocol change
        if (redirUrl.startsWith("http://")) {
            log.trace("Changing protocol to HTTP");
            return redirUrl;
        }
    }

    return url;
}

From source file:javafxpert.conceptmap.alexa.ConceptMapSpeechlet.java

/**
 * Call a ConceptMap endpoint to retrieve related claims
 *
 * @throws IOException/*from  w ww  . j a va  2 s.  c o  m*/
 */
//private SpeechletResponse makeClaimsRequest(String itemId, String propId) {
private SpeechletResponse makeClaimsRequest(String itemValue, String relationshipValue) {
    String properCasedItemValue = WordUtils.capitalize(itemValue);
    String speechOutput = "";
    Image image = new Image();

    // Translate requested item and relationship to Q and P numbers
    //String itemId = "Q887401";
    String propId = "P54";
    String itemId = locateItemId(properCasedItemValue);
    if (itemId != null && itemId.length() > 0) {

        String queryString = String.format("?id=%s&direction=f&prop=%s&depth=1", itemId, propId);

        InputStreamReader inputStream = null;
        BufferedReader bufferedReader = null;
        StringBuilder builder = new StringBuilder();
        try {
            String line;
            URL url = new URL(TRAVERSAL_ENDPOINT + queryString);
            inputStream = new InputStreamReader(url.openStream(), Charset.forName("US-ASCII"));
            bufferedReader = new BufferedReader(inputStream);
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            // reset builder to a blank string
            builder.setLength(0);
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(bufferedReader);

            log.info("builder: " + builder);
        }

        if (builder.length() == 0) {
            speechOutput = "Sorry, the Concept Map claims service is experiencing a problem. "
                    + "Please try again later.";
        } else {
            try {
                JSONObject claimsResponseObject = new JSONObject(new JSONTokener(builder.toString()));

                if (claimsResponseObject != null) {
                    ClaimsInfo claimsInfo = createClaimsInfo(claimsResponseObject, itemId);

                    log.info("claimsInfo: " + claimsInfo);

                    speechOutput = "Item " + properCasedItemValue + " not found";

                    if (claimsInfo.getItemLabels().size() > 0) {
                        speechOutput = new StringBuilder().append(properCasedItemValue)
                                //.append(claimsInfo.getItemLabels().get(0))
                                .append(" has been a member of ").append(relationshipValue).append(" \n")
                                .append(claimsInfo.toItemLabelsSpeech()).toString();
                    }

                    // Get the picture redirect
                    URL url = new URL(claimsInfo.getPictureUrl());
                    HttpURLConnection.setFollowRedirects(false);
                    final HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    //con.setInstanceFollowRedirects(false);
                    final int responseCode = con.getResponseCode();
                    final String redirectLocation = con.getHeaderField("Location");
                    image.setSmallImageUrl(redirectLocation);
                }
                //} catch (JSONException | ParseException e) {
            } catch (JSONException | IOException e) {
                log.error("Exception occoured while parsing service response.", e);
            }
        }
    } else {
        speechOutput = "Couldn't locate an Item ID for item " + properCasedItemValue;
    }

    // Create the Simple card content.
    StandardCard card = new StandardCard();
    card.setTitle(properCasedItemValue);
    card.setText(speechOutput);
    card.setImage(image);
    // Create the plain text output
    PlainTextOutputSpeech outputSpeech = new PlainTextOutputSpeech();
    outputSpeech.setText(speechOutput);

    return SpeechletResponse.newTellResponse(outputSpeech, card);
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImplClassifier.java

protected void disconnect(HttpURLConnection conn) {
    if (conn != null) {
        String connection = conn.getHeaderField(HTTPConstants.HEADER_CONNECTION);
        String protocol = conn.getHeaderField(0);
        if ((connection == null && (protocol == null || !protocol.startsWith(HTTPConstants.HTTP_1_1)))
                || (connection != null && connection.equalsIgnoreCase(HTTPConstants.CONNECTION_CLOSE))) {
            conn.disconnect();/*from w  w w  . ja va 2s  . co m*/
        } // TODO ? perhaps note connection so it can be disconnected at end
          // of test?
    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java

/**
 * Gets the ResponseHeaders from the URLConnection
 *
 * @param conn//from w w  w.  j  a v a 2  s.  c  o  m
 *            connection from which the headers are read
 * @return string containing the headers, one per line
 */
protected String getResponseHeaders(HttpURLConnection conn) {
    StringBuilder headerBuf = new StringBuilder();
    headerBuf.append(conn.getHeaderField(0));// Leave header as is
    // headerBuf.append(conn.getHeaderField(0).substring(0, 8));
    // headerBuf.append(" ");
    // headerBuf.append(conn.getResponseCode());
    // headerBuf.append(" ");
    // headerBuf.append(conn.getResponseMessage());
    headerBuf.append("\n"); //$NON-NLS-1$

    String hfk;
    for (int i = 1; (hfk = conn.getHeaderFieldKey(i)) != null; i++) {
        headerBuf.append(hfk);
        headerBuf.append(": "); // $NON-NLS-1$
        headerBuf.append(conn.getHeaderField(i));
        headerBuf.append("\n"); // $NON-NLS-1$
    }
    return headerBuf.toString();
}