Example usage for java.net HttpURLConnection addRequestProperty

List of usage examples for java.net HttpURLConnection addRequestProperty

Introduction

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

Prototype

public void addRequestProperty(String key, String value) 

Source Link

Document

Adds a general request property specified by a key-value pair.

Usage

From source file:com.castlemock.web.mock.soap.web.soap.controller.AbstractSoapServiceController.java

/**
 * The method provides the functionality to forward request to a forwarded endpoint.
 * @param request The request that will be forwarded
 * @param soapOperationDto The SOAP operation that is being executed
 * @return The response from the system that the request was forwarded to.
 *//*from w w w  . j av a2s  .c  o  m*/
private SoapResponseDto forwardRequest(final SoapRequestDto request, final String soapProjectId,
        final String soapPortId, final SoapOperationDto soapOperationDto) {
    if (demoMode) {
        // If the application is configured to run in demo mode, then use mocked response instead
        return mockResponse(soapProjectId, soapPortId, soapOperationDto);
    }

    final SoapResponseDto response = new SoapResponseDto();
    HttpURLConnection connection = null;
    OutputStream outputStream = null;
    BufferedReader bufferedReader = null;
    try {
        final URL url = new URL(soapOperationDto.getForwardedEndpoint());
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(request.getHttpMethod().name());
        for (HttpHeaderDto httpHeader : request.getHttpHeaders()) {
            connection.addRequestProperty(httpHeader.getName(), httpHeader.getValue());
        }

        outputStream = connection.getOutputStream();
        outputStream.write(request.getBody().getBytes());
        outputStream.flush();

        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        final StringBuilder stringBuilder = new StringBuilder();
        String buffer;
        while ((buffer = bufferedReader.readLine()) != null) {
            stringBuilder.append(buffer);
            stringBuilder.append(NEW_LINE);
        }

        final List<HttpHeaderDto> responseHttpHeaders = HttpMessageSupport.extractHttpHeaders(connection);
        response.setMockResponseName(FORWARDED_RESPONSE_NAME);
        response.setBody(stringBuilder.toString());
        response.setHttpHeaders(responseHttpHeaders);
        response.setHttpStatusCode(connection.getResponseCode());
        return response;
    } catch (IOException exception) {
        LOGGER.error("Unable to forward request", exception);
        throw new SoapException("Unable to forward request to configured endpoint");
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException exception) {
                LOGGER.error("Unable to close output stream", exception);
            }
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException exception) {
                LOGGER.error("Unable to close buffered reader", exception);
            }
        }
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.util.Fetcher.java

protected HttpURLConnection getConnection(final String url, final String data, final String requestMethod,
        final long lastFetchTime) throws IOException {
    String method = GET_STR;/*from ww w.j  av  a2 s  .  c  o  m*/

    if (requestMethod != null) {
        method = requestMethod;
    }

    LOGGER.info(method + "ing: " + url + "; timeout is " + timeout);

    final URLConnection connection = new URL(url).openConnection();

    connection.setIfModifiedSince(lastFetchTime);

    if (timeout != 0) {
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
    }

    final HttpURLConnection http = (HttpURLConnection) connection;

    if (connection instanceof HttpsURLConnection) {
        final HttpsURLConnection https = (HttpsURLConnection) connection;
        https.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
        });
    }

    http.setInstanceFollowRedirects(false);
    http.setRequestMethod(method);
    http.setAllowUserInteraction(true);

    for (final String key : requestProps.keySet()) {
        http.addRequestProperty(key, requestProps.get(key));
    }

    if (method.equals(POST_STR) && data != null) {
        http.setDoOutput(true); // Triggers POST.

        try (final OutputStream output = http.getOutputStream()) {
            output.write(data.getBytes(UTF8_STR));
        }
    }

    connection.connect();

    return http;
}

From source file:ai.api.AIDataService.java

/**
 * Method extracted for testing purposes
 *//*from w w w. j  a  va  2 s.  c  o m*/
protected String doSoundRequest(@NonNull final InputStream voiceStream, @NonNull final String queryData,
        @Nullable final Map<String, String> additionalHeaders)
        throws MalformedURLException, AIServiceException {

    HttpURLConnection connection = null;
    HttpClient httpClient = null;

    try {
        final URL url = new URL(config.getQuestionUrl());

        if (config.getProxy() != null) {
            connection = (HttpURLConnection) url.openConnection(config.getProxy());
        } else {
            connection = (HttpURLConnection) url.openConnection();
        }

        connection.addRequestProperty("Authorization", "Bearer " + config.getApiKey());
        connection.addRequestProperty("Accept", "application/json");

        if (additionalHeaders != null) {
            for (final Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
                connection.addRequestProperty(entry.getKey(), entry.getValue());
            }
        }

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

        httpClient = new HttpClient(connection);
        httpClient.setWriteSoundLog(config.isWriteSoundLog());

        httpClient.connectForMultipart();
        httpClient.addFormPart("request", queryData);
        httpClient.addFilePart("voiceData", "voice.wav", voiceStream);
        httpClient.finishMultipart();

        final String response = httpClient.getResponse();
        return response;

    } catch (final IOException e) {

        if (httpClient != null) {
            final String errorString = httpClient.getErrorString();
            Log.d(TAG, "" + errorString);
            if (!TextUtils.isEmpty(errorString)) {
                return errorString;
            } else if (e instanceof HttpRetryException) {
                final AIResponse response = new AIResponse();
                final int code = ((HttpRetryException) e).responseCode();
                final Status status = Status.fromResponseCode(code);
                status.setErrorDetails(((HttpRetryException) e).getReason());
                response.setStatus(status);
                throw new AIServiceException(response);
            }
        }

        Log.e(TAG,
                "Can't make request to the API.AI service. Please, check connection settings and API.AI keys.",
                e);
        throw new AIServiceException(
                "Can't make request to the API.AI service. Please, check connection settings and API.AI keys.",
                e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:fr.xebia.servlet.filter.XForwardedFilterTest.java

/**
 * Test {@link XForwardedFilter} in Jetty
 *//*  ww  w  .  java 2 s . c o  m*/
@Test
public void testWithJetty() throws Exception {

    // SETUP
    int port = 6666;
    Server server = new Server(port);
    Context context = new Context(server, "/", Context.SESSIONS);

    // mostly default configuration : enable "x-forwarded-proto"
    XForwardedFilter xforwardedFilter = new XForwardedFilter();
    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.addInitParameter(XForwardedFilter.PROTOCOL_HEADER_PARAMETER, "x-forwarded-proto");
    // Following is needed on ipv6 stacks..
    filterConfig.addInitParameter(XForwardedFilter.INTERNAL_PROXIES_PARAMETER,
            InetAddress.getByName("localhost").getHostAddress());
    xforwardedFilter.init(filterConfig);
    context.addFilter(new FilterHolder(xforwardedFilter), "/*", Handler.REQUEST);

    MockHttpServlet mockServlet = new MockHttpServlet();
    context.addServlet(new ServletHolder(mockServlet), "/test");

    server.start();
    try {
        // TEST
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test")
                .openConnection();
        String expectedRemoteAddr = "my-remote-addr";
        httpURLConnection.addRequestProperty("x-forwarded-for", expectedRemoteAddr);
        httpURLConnection.addRequestProperty("x-forwarded-proto", "https");

        // VALIDATE

        Assert.assertEquals(HttpURLConnection.HTTP_OK, httpURLConnection.getResponseCode());
        HttpServletRequest request = mockServlet.getRequest();
        Assert.assertNotNull(request);

        // VALIDATE X-FOWARDED-FOR
        Assert.assertEquals(expectedRemoteAddr, request.getRemoteAddr());
        Assert.assertEquals(expectedRemoteAddr, request.getRemoteHost());

        // VALIDATE X-FORWARDED-PROTO
        Assert.assertTrue(request.isSecure());
        Assert.assertEquals("https", request.getScheme());
        Assert.assertEquals(443, request.getServerPort());
    } finally {
        server.stop();
    }
}

From source file:org.runnerup.export.RunKeeperSynchronizer.java

@Override
public ActivityEntity download(SyncActivityItem item) {
    ActivityEntity activity = new ActivityEntity();
    Status s = connect();//from  w ww . j  a  v a2 s . c  o m
    if (s != Status.OK) {
        return null;
    }

    HttpURLConnection conn = null;
    try {
        URL activityUrl = new URL(item.getURI());
        conn = (HttpURLConnection) activityUrl.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod(RequestMethod.GET.name());
        conn.addRequestProperty("Authorization", "Bearer " + access_token);
        conn.addRequestProperty("Content-type", "application/vnd.com.runkeeper.FitnessActivity+json");

        if (conn.getResponseCode() == HttpStatus.SC_OK) {
            BufferedInputStream input = new BufferedInputStream(conn.getInputStream());
            JSONObject resp = SyncHelper.parse(input);
            activity = RunKeeper.parseToActivity(resp, getLapLength());
        }

    } catch (IOException e) {
        Log.e(Constants.LOG, e.getMessage());
        return activity;

    } catch (JSONException e) {
        Log.e(Constants.LOG, e.getMessage());
        return activity;
    }
    return activity;
}

From source file:com.fivehundredpxdemo.android.storage.ImageFetcher.java

/**
 * Download a bitmap from a URL and write the content to an output stream.
 *
 * @param urlString The URL to fetch/*from  w w w .java2s .c o m*/
 * @param outputStream The outputStream to write to
 * @return true if successful, false otherwise
 */
public boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
    disableConnectionReuseIfNecessary();
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;

    try {
        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.addRequestProperty("Authorization", "Bearer " + accessToken);
        in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
        out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE_BYTES);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        return true;
    } catch (final IOException e) {
        Log.e(TAG, "Error in downloadBitmap - " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (final IOException e) {
        }
    }
    return false;
}

From source file:yandexDisk.YandexDiskAPI.java

public String connectWithREST(String url, String method)
        throws IOException, ProtocolException, MalformedURLException {
    String newURL = "";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // Connect with a REST Method: GET, DELETE
    con.setRequestMethod(method);//from   www.j  a va 2 s .  c  o  m
    //add request header
    con.setReadTimeout(20000);
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.addRequestProperty("Authorization", auth.getAuthorizationHeader());
    int responseCode = con.getResponseCode();
    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 (method.equals(GET)) {
        newURL = splitURL(response.toString());
    }
    if (getSize) {
        newURL = response.toString();
        getSize = false;
    }
    return newURL;
}

From source file:export.NikePlus.java

@Override
public Status upload(SQLiteDatabase db, long mID) {
    Status s;/*from   w ww .j  a  va 2s  .  c om*/
    if ((s = connect()) != Status.OK) {
        return s;
    }

    NikeXML nikeXML = new NikeXML(db);
    GPX nikeGPX = new GPX(db);
    HttpURLConnection conn = null;
    Exception ex = null;
    try {
        StringWriter xml = new StringWriter();
        nikeXML.export(mID, xml);

        StringWriter gpx = new StringWriter();
        nikeGPX.export(mID, gpx);

        String url = String.format(SYNC_URL, access_token);
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("user-agent", USER_AGENT);
        conn.addRequestProperty("appid", APP_ID);
        Part<StringWritable> part1 = new Part<StringWritable>("runXML", new StringWritable(xml.toString()));
        part1.filename = "runXML.xml";
        part1.contentType = "text/plain; charset=US-ASCII";
        part1.contentTransferEncoding = "8bit";

        Part<StringWritable> part2 = new Part<StringWritable>("gpxXML", new StringWritable(gpx.toString()));
        part2.filename = "gpxXML.xml";
        part2.contentType = "text/plain; charset=US-ASCII";
        part2.contentTransferEncoding = "8bit";

        Part<?> parts[] = { part1, part2 };
        postMulti(conn, parts);
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        conn.connect();

        if (responseCode != 200) {
            throw new Exception(amsg);
        }

        url = String.format(SYNC_COMPLETE_URL, access_token);
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("user-agent", USER_AGENT);
        conn.addRequestProperty("appid", APP_ID);

        responseCode = conn.getResponseCode();
        amsg = conn.getResponseMessage();
        conn.disconnect();
        if (responseCode == 200) {
            return Status.OK;
        }

        ex = new Exception(amsg);
    } catch (Exception e) {
        ex = e;
    }

    s = Uploader.Status.ERROR;
    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

From source file:yandexDisk.YandexDiskAPI.java

private void uploadFileByPUT(String theUrl, File file) throws Exception {
    // File file = new File("img.jpg");
    URL obj = new URL(theUrl);

    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is PUT
    con.setRequestMethod("PUT");
    con.setDoOutput(true);//w  ww  .  ja  v  a2 s .c o  m

    //add request header
    con.setReadTimeout(20000);
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.addRequestProperty("Authorization", auth.getAuthorizationHeader());

    long size = file.length();
    FileInputStream inputStream = new FileInputStream(file);

    boolean isTrue = uploadFile(theUrl, inputStream, size);

    int responseCode = con.getResponseCode();
}

From source file:tree.love.providers.downloads.DownloadThread.java

/**
 * Add custom headers for this download to the HTTP request.
 *//*from w ww  .  j a  v a 2  s.  c  o m*/
private void addRequestHeaders(State state, HttpURLConnection conn) {
    for (Pair<String, String> header : mInfo.getHeaders()) {
        conn.addRequestProperty(header.first, header.second);
    }

    // Only splice in user agent when not already defined
    if (conn.getRequestProperty("User-Agent") == null) {
        conn.addRequestProperty("User-Agent", userAgent());
    }

    // Defeat transparent gzip compression, since it doesn't allow us to
    // easily resume partial downloads.
    conn.setRequestProperty("Accept-Encoding", "identity");

    if (state.mContinuingDownload) {
        if (state.mHeaderETag != null) {
            conn.addRequestProperty("If-Match", state.mHeaderETag);
        }
        conn.addRequestProperty("Range", "bytes=" + state.mCurrentBytes + "-");
    }
}