java.net.HttpURLConnection

Here are the examples of the java api class java.net.HttpURLConnection taken from open source projects.

1. RemoteSSOService#getAuthConnection()

Project: datacollector
Source File: RemoteSSOService.java
View license
HttpURLConnection getAuthConnection(String method, String url) throws IOException {
    HttpURLConnection conn = createAuthConnection(url);
    conn.setRequestMethod(method);
    switch(method) {
        case "POST":
        case "PUT":
            conn.setDoOutput(true);
        case "GET":
            conn.setDoInput(true);
    }
    conn.setUseCaches(false);
    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);
    conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON);
    conn.setRequestProperty(ACCEPT, APPLICATION_JSON);
    conn.setRequestProperty(SSOConstants.X_REST_CALL, "-");
    conn.setRequestProperty(SSOConstants.X_APP_AUTH_TOKEN, appToken);
    conn.setRequestProperty(SSOConstants.X_APP_COMPONENT_ID, componentId);
    return conn;
}

2. JsonRpcHttpClient#prepareConnection()

Project: jsonrpc4j
Source File: JsonRpcHttpClient.java
View license
/**
	 * Prepares a connection to the server.
	 * @param extraHeaders extra headers to add to the request
	 * @return the unopened connection
	 * @throws IOException
	 */
private HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {
    // create URLConnection
    HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
    connection.setConnectTimeout(connectionTimeoutMillis);
    connection.setReadTimeout(readTimeoutMillis);
    connection.setAllowUserInteraction(false);
    connection.setDefaultUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(true);
    connection.setRequestMethod("POST");
    setupSsl(connection);
    addHeaders(extraHeaders, connection);
    return connection;
}

3. HttpKitExt#downloadMaterial()

Project: weixin
Source File: HttpKitExt.java
View license
/**
	 * ??????
	 * @param url ????
	 * @return params post??
	 * @return InputStream ???????????json?file
	 * @throws IOException
	 */
protected static InputStream downloadMaterial(String url, String params) throws IOException {
    URL _url = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
    // ????
    conn.setConnectTimeout(25000);
    // ???? --?????????????
    conn.setReadTimeout(25000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "Keep-Alive");
    conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.connect();
    if (StrKit.notBlank(params)) {
        OutputStream out = conn.getOutputStream();
        out.write(params.getBytes(Charsets.UTF_8));
        out.flush();
        IOUtils.closeQuietly(out);
    }
    return conn.getInputStream();
}

4. DefaultStreamWriter#createBatchWriter()

Project: cdap
Source File: DefaultStreamWriter.java
View license
@Override
public StreamBatchWriter createBatchWriter(String stream, String contentType) throws IOException {
    URL url = getStreamURL(stream, true);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.POST.name());
    connection.setReadTimeout(15000);
    connection.setConnectTimeout(15000);
    connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType);
    connection.setDoOutput(true);
    connection.setChunkedStreamingMode(0);
    connection.connect();
    try {
        Id.Stream streamId = Id.Stream.from(namespace, stream);
        registerStream(streamId);
        return new DefaultStreamBatchWriter(connection, streamId);
    } catch (IOException e) {
        connection.disconnect();
        throw e;
    }
}

5. ITNProxy#post()

Project: consulo
Source File: ITNProxy.java
View license
private static HttpURLConnection post(URL url, byte[] bytes) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) HttpConfigurable.getInstance().openConnection(url.toString());
    connection.setReadTimeout(10 * 1000);
    connection.setConnectTimeout(10 * 1000);
    connection.setRequestMethod(HTTP_POST);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestProperty(HTTP_CONTENT_TYPE, String.format("%s; charset=%s", HTTP_WWW_FORM, ENCODING));
    connection.setRequestProperty(HTTP_CONTENT_LENGTH, Integer.toString(bytes.length));
    OutputStream out = new BufferedOutputStream(connection.getOutputStream());
    try {
        out.write(bytes);
        out.flush();
    } finally {
        out.close();
    }
    return connection;
}

6. AsyncQueryForwardingServletTest#testProxyGzipCompression()

View license
@Test
public void testProxyGzipCompression() throws Exception {
    final URL url = new URL("http://localhost:" + port + "/proxy/default");
    final HttpURLConnection get = (HttpURLConnection) url.openConnection();
    get.setRequestProperty("Accept-Encoding", "gzip");
    Assert.assertEquals("gzip", get.getContentEncoding());
    final HttpURLConnection post = (HttpURLConnection) url.openConnection();
    post.setRequestProperty("Accept-Encoding", "gzip");
    post.setRequestMethod("POST");
    Assert.assertEquals("gzip", post.getContentEncoding());
    final HttpURLConnection getNoGzip = (HttpURLConnection) url.openConnection();
    Assert.assertNotEquals("gzip", getNoGzip.getContentEncoding());
    final HttpURLConnection postNoGzip = (HttpURLConnection) url.openConnection();
    postNoGzip.setRequestMethod("POST");
    Assert.assertNotEquals("gzip", postNoGzip.getContentEncoding());
}

7. JettyTest#testGzipCompression()

Project: druid
Source File: JettyTest.java
View license
@Test
public void testGzipCompression() throws Exception {
    final URL url = new URL("http://localhost:" + port + "/default");
    final HttpURLConnection get = (HttpURLConnection) url.openConnection();
    get.setRequestProperty("Accept-Encoding", "gzip");
    Assert.assertEquals("gzip", get.getContentEncoding());
    final HttpURLConnection post = (HttpURLConnection) url.openConnection();
    post.setRequestProperty("Accept-Encoding", "gzip");
    post.setRequestMethod("POST");
    Assert.assertEquals("gzip", post.getContentEncoding());
    final HttpURLConnection getNoGzip = (HttpURLConnection) url.openConnection();
    Assert.assertNotEquals("gzip", getNoGzip.getContentEncoding());
    final HttpURLConnection postNoGzip = (HttpURLConnection) url.openConnection();
    postNoGzip.setRequestMethod("POST");
    Assert.assertNotEquals("gzip", postNoGzip.getContentEncoding());
}

8. RESTServiceTest#xqueryGetFailWithNonEmptyPath()

Project: exist
Source File: RESTServiceTest.java
View license
@Test
public void xqueryGetFailWithNonEmptyPath() throws IOException {
    /* store the documents that we need for this test */
    HttpURLConnection sconnect = getConnection(RESOURCE_URI);
    sconnect.setRequestProperty("Authorization", "Basic " + credentials);
    sconnect.setRequestMethod("PUT");
    sconnect.setDoOutput(true);
    sconnect.setRequestProperty("ContentType", "application/xml");
    Writer writer = new OutputStreamWriter(sconnect.getOutputStream(), "UTF-8");
    writer.write(XML_DATA);
    writer.close();
    // should not be able to get this path
    String path = RESOURCE_URI + "/some/path";
    HttpURLConnection connect = getConnection(path);
    connect.setRequestMethod("GET");
    connect.connect();
    int r = connect.getResponseCode();
    assertEquals("Server returned response code " + r, 404, r);
}

9. Downloader#createConnection()

Project: graphhopper
Source File: Downloader.java
View license
public HttpURLConnection createConnection(String urlStr) throws IOException {
    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // Will yield in a POST request: conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(true);
    conn.setRequestProperty("Referrer", referrer);
    conn.setRequestProperty("User-Agent", userAgent);
    // suggest respond to be gzipped or deflated (which is just another compression)
    // http://stackoverflow.com/q/3932117
    conn.setRequestProperty("Accept-Encoding", acceptEncoding);
    conn.setReadTimeout(timeout);
    conn.setConnectTimeout(timeout);
    return conn;
}

10. B6401598#getHttpURLConnection()

Project: jdk7u-jdk
Source File: B6401598.java
View license
static HttpURLConnection getHttpURLConnection(URL url, int timeout) throws IOException {
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setConnectTimeout(40000);
    httpURLConnection.setReadTimeout(timeout);
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setDoInput(true);
    httpURLConnection.setUseCaches(false);
    httpURLConnection.setAllowUserInteraction(false);
    httpURLConnection.setRequestMethod("POST");
    return httpURLConnection;
}

11. HttpPostMethod#openConnectionInternal()

Project: lumify
Source File: HttpPostMethod.java
View license
@Override
public HttpURLConnection openConnectionInternal() throws IOException {
    Charset utf8 = Charset.forName("UTF-8");
    byte[] data = getParameterString().getBytes(utf8);
    HttpURLConnection conn = (HttpURLConnection) getBaseUrl().openConnection();
    conn.setUseCaches(shouldUseCaches());
    conn.setInstanceFollowRedirects(shouldFollowRedirects());
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("charset", utf8.toString());
    conn.setRequestProperty("Content-Length", Integer.toString(data.length));
    new DataOutputStream(conn.getOutputStream()).write(data);
    return conn;
}

12. ResponseCacheTest#varyMultipleFieldsWithMatch()

Project: okhttp
Source File: ResponseCacheTest.java
View license
@Test
public void varyMultipleFieldsWithMatch() throws Exception {
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").addHeader("Vary: Accept-Language, Accept-Charset").addHeader("Vary: Accept-Encoding").setBody("A"));
    server.enqueue(new MockResponse().setBody("B"));
    URL url = server.url("/").url();
    HttpURLConnection frenchConnection1 = openConnection(url);
    frenchConnection1.setRequestProperty("Accept-Language", "fr-CA");
    frenchConnection1.setRequestProperty("Accept-Charset", "UTF-8");
    frenchConnection1.setRequestProperty("Accept-Encoding", "identity");
    assertEquals("A", readAscii(frenchConnection1));
    HttpURLConnection frenchConnection2 = openConnection(url);
    frenchConnection2.setRequestProperty("Accept-Language", "fr-CA");
    frenchConnection2.setRequestProperty("Accept-Charset", "UTF-8");
    frenchConnection2.setRequestProperty("Accept-Encoding", "identity");
    assertEquals("A", readAscii(frenchConnection2));
}

13. ResponseCacheTest#varyMultipleFieldsWithNoMatch()

Project: okhttp
Source File: ResponseCacheTest.java
View license
@Test
public void varyMultipleFieldsWithNoMatch() throws Exception {
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").addHeader("Vary: Accept-Language, Accept-Charset").addHeader("Vary: Accept-Encoding").setBody("A"));
    server.enqueue(new MockResponse().setBody("B"));
    URL url = server.url("/").url();
    HttpURLConnection frenchConnection = openConnection(url);
    frenchConnection.setRequestProperty("Accept-Language", "fr-CA");
    frenchConnection.setRequestProperty("Accept-Charset", "UTF-8");
    frenchConnection.setRequestProperty("Accept-Encoding", "identity");
    assertEquals("A", readAscii(frenchConnection));
    HttpURLConnection englishConnection = openConnection(url);
    englishConnection.setRequestProperty("Accept-Language", "en-CA");
    englishConnection.setRequestProperty("Accept-Charset", "UTF-8");
    englishConnection.setRequestProperty("Accept-Encoding", "identity");
    assertEquals("B", readAscii(englishConnection));
}

14. B6401598#getHttpURLConnection()

Project: openjdk
Source File: B6401598.java
View license
static HttpURLConnection getHttpURLConnection(URL url, int timeout) throws IOException {
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setConnectTimeout(40000);
    httpURLConnection.setReadTimeout(timeout);
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setDoInput(true);
    httpURLConnection.setUseCaches(false);
    httpURLConnection.setAllowUserInteraction(false);
    httpURLConnection.setRequestMethod("POST");
    return httpURLConnection;
}

15. HttpClient#init()

Project: braintree_android
Source File: HttpClient.java
View license
protected HttpURLConnection init(String url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    if (connection instanceof HttpsURLConnection) {
        if (mSSLSocketFactory == null) {
            throw new SSLException("SSLSocketFactory was not set or failed to initialize");
        }
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSSLSocketFactory);
    }
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("User-Agent", mUserAgent);
    connection.setRequestProperty("Accept-Language", Locale.getDefault().getLanguage());
    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setConnectTimeout(mConnectTimeout);
    connection.setReadTimeout(mReadTimeout);
    return connection;
}

16. RESTServiceTest#uploadData()

Project: exist
Source File: RESTServiceTest.java
View license
private int uploadData() throws IOException {
    HttpURLConnection connect = getConnection(RESOURCE_URI);
    connect.setRequestProperty("Authorization", "Basic " + credentials);
    connect.setRequestMethod("PUT");
    connect.setDoOutput(true);
    connect.setRequestProperty("ContentType", "application/xml");
    Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8");
    writer.write(XML_DATA);
    writer.close();
    connect.connect();
    return connect.getResponseCode();
}

17. RESTServiceTest#uploadDataPlus()

Project: exist
Source File: RESTServiceTest.java
View license
private int uploadDataPlus() throws IOException {
    HttpURLConnection connect = getConnection(RESOURCE_URI_PLUS);
    connect.setRequestProperty("Authorization", "Basic " + credentials);
    connect.setRequestMethod("PUT");
    connect.setDoOutput(true);
    connect.setRequestProperty("ContentType", "application/xml");
    Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8");
    writer.write(XML_DATA);
    writer.close();
    connect.connect();
    return connect.getResponseCode();
}

18. SimpleConsumerTest#sendMessageByHttp()

Project: jafka
Source File: SimpleConsumerTest.java
View license
//    @Test
//    public void testCreatePartitions() throws IOException{
//        int size = consumer.createPartitions("demo", partitions-1, false);
//        assertEquals(partitions, size);
//        size = consumer.createPartitions("demo", partitions+1, false);
//        assertEquals(partitions, size);
//        size = consumer.createPartitions("demo", partitions+3, true);
//        assertEquals(partitions, size);
//        //
//        final String largePartitionTopic = "largepartition";
//        size = consumer.createPartitions(largePartitionTopic, partitions+5, true);
//        assertEquals(partitions+5, size);
//        sendSomeMessages(1000, largePartitionTopic);
//    }
private void sendMessageByHttp(int port, String topic, int partition, byte[] data) throws IOException {
    URL url = new URL(String.format("http://127.0.0.1:%s/", port));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("request_key", "PRODUCE");
    conn.setRequestProperty("topic", topic);
    conn.setRequestProperty("partition", "" + partition);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    //
    conn.getOutputStream().write(data);
    conn.getOutputStream().flush();
    conn.getOutputStream().close();
    //
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    assertEquals("OK", reader.readLine());
    reader.close();
}

19. StockQuote#setUpHttpConnection()

Project: wicket
Source File: StockQuote.java
View license
/**
	 * Sets up the HTTP connection.
	 * 
	 * @param url
	 *            the url to connect to
	 * @param length
	 *            the length to the input message
	 * @return the HttpurLConnection
	 * @throws IOException
	 * @throws ProtocolException
	 */
private HttpURLConnection setUpHttpConnection(URL url, int length) throws IOException {
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConn = (HttpURLConnection) connection;
    // Set the appropriate HTTP parameters.
    httpConn.setRequestProperty("Content-Length", String.valueOf(length));
    httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
    httpConn.setRequestProperty("SOAPAction", "\"http://www.webserviceX.NET/GetQuote\"");
    httpConn.setRequestMethod("POST");
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    return httpConn;
}

20. HttpURLConnectionHandler#openConnection()

Project: wink
Source File: HttpURLConnectionHandler.java
View license
private HttpURLConnection openConnection(ClientRequest request) throws IOException {
    URL url = request.getURI().toURL();
    HttpURLConnection connection = null;
    // we're on the client so this is a safe cast
    ClientConfig config = (ClientConfig) request.getAttribute(WinkConfiguration.class);
    // setup proxy
    if (config.getProxyHost() != null) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getProxyHost(), config.getProxyPort()));
        connection = (HttpURLConnection) url.openConnection(proxy);
    } else {
        connection = (HttpURLConnection) url.openConnection();
    }
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestMethod(request.getMethod());
    connection.setConnectTimeout(config.getConnectTimeout());
    connection.setReadTimeout(config.getReadTimeout());
    connection.setInstanceFollowRedirects(config.isFollowRedirects());
    return connection;
}

21. EC2MetadataClient#readResource()

Project: aws-sdk-java
Source File: EC2MetadataClient.java
View license
/**
     * Connects to the metadata service to read the specified resource and
     * returns the text contents.
     *
     * @param resourcePath
     *            The resource
     *
     * @return The text payload returned from the Amazon EC2 Instance Metadata
     *         service for the specified resource path.
     *
     * @throws IOException
     *             If any problems were encountered while connecting to metadata
     *             service for the requested resource path.
     * @throws AmazonClientException
     *             If the requested metadata service is not found.
     */
public String readResource(String resourcePath) throws IOException, AmazonClientException {
    URL url = getEc2MetadataServiceUrlForResource(resourcePath);
    log.debug("Connecting to EC2 instance metadata service at URL: " + url.toString());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(1000 * 2);
    connection.setReadTimeout(1000 * 5);
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.connect();
    return readResponse(connection);
}

22. HtmlFetcher#createUrlConnection()

Project: browser-android
Source File: HtmlFetcher.java
View license
protected HttpURLConnection createUrlConnection(String urlAsStr, int timeout, boolean includeSomeGooseOptions) throws MalformedURLException, IOException {
    URL url = new URL(urlAsStr);
    //using proxy may increase latency
    HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
    hConn.setRequestProperty("User-Agent", userAgent);
    hConn.setRequestProperty("Accept", accept);
    if (includeSomeGooseOptions) {
        hConn.setRequestProperty("Accept-Language", language);
        hConn.setRequestProperty("content-charset", charset);
        hConn.addRequestProperty("Referer", referrer);
        // avoid the cache for testing purposes only?
        hConn.setRequestProperty("Cache-Control", cacheControl);
    }
    // suggest respond to be gzipped or deflated (which is just another compression)
    // http://stackoverflow.com/q/3932117
    hConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    hConn.setConnectTimeout(timeout);
    hConn.setReadTimeout(timeout);
    return hConn;
}

23. DynamicMetadataResolverAdapter#getResourceInputStream()

View license
@Override
protected InputStream getResourceInputStream(final Resource resource, final String entityId) throws IOException {
    final String encodedId = EncodingUtils.urlEncode(entityId);
    final URL url = new URL(resource.getURL().toExternalForm().concat(encodedId));
    final HttpURLConnection httpcon = (HttpURLConnection) (url.openConnection());
    httpcon.setDoOutput(true);
    httpcon.addRequestProperty("Accept", "*/*");
    httpcon.setRequestMethod("GET");
    httpcon.connect();
    return httpcon.getInputStream();
}

24. RESTServiceTest#putFailAgainstCollection()

Project: exist
Source File: RESTServiceTest.java
View license
@Test
public void putFailAgainstCollection() throws IOException {
    HttpURLConnection connect = getConnection(COLLECTION_URI);
    connect.setRequestProperty("Authorization", "Basic " + credentials);
    connect.setRequestMethod("PUT");
    connect.setDoOutput(true);
    connect.setRequestProperty("ContentType", "application/xml");
    Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8");
    writer.write(XML_DATA);
    writer.close();
    connect.connect();
    int r = connect.getResponseCode();
    assertEquals("Server returned response code " + r, 400, r);
}

25. RESTServiceTest#putWithCharset()

Project: exist
Source File: RESTServiceTest.java
View license
@Test
public void putWithCharset() throws IOException {
    HttpURLConnection connect = getConnection(RESOURCE_URI);
    connect.setRequestProperty("Authorization", "Basic " + credentials);
    connect.setRequestMethod("PUT");
    connect.setDoOutput(true);
    connect.setRequestProperty("ContentType", "application/xml; charset=UTF-8");
    Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8");
    writer.write(XML_DATA);
    writer.close();
    connect.connect();
    int r = connect.getResponseCode();
    assertEquals("Server returned response code " + r, 201, r);
    doGet();
}

26. RESTServiceTest#putFailAndRechallengeAuthorization()

Project: exist
Source File: RESTServiceTest.java
View license
@Test
public void putFailAndRechallengeAuthorization() throws IOException {
    HttpURLConnection connect = getConnection(RESOURCE_URI);
    connect.setRequestProperty("Authorization", "Basic " + badCredentials);
    connect.setDoOutput(true);
    connect.setRequestMethod("PUT");
    connect.setAllowUserInteraction(false);
    connect.connect();
    int r = connect.getResponseCode();
    assertEquals("Server returned response code " + r, 401, r);
    String auth = connect.getHeaderField("WWW-Authenticate");
    assertEquals("WWW-Authenticate = " + auth, "Basic realm=\"exist\"", auth);
}

27. RESTServiceTest#putAgainstXQuery()

Project: exist
Source File: RESTServiceTest.java
View license
@Test
public void putAgainstXQuery() throws IOException {
    doPut(TEST_XQUERY_WITH_PATH_AND_CONTENT, "requestwithcontent.xq", 201);
    String path = COLLECTION_URI_REDIRECTED + "/requestwithcontent.xq/a/b/c";
    HttpURLConnection connect = getConnection(path);
    connect.setRequestProperty("Authorization", "Basic " + credentials);
    connect.setRequestMethod("PUT");
    connect.setDoOutput(true);
    connect.setRequestProperty("ContentType", "application/xml");
    Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8");
    writer.write("<data>test data</data>");
    writer.close();
    connect.connect();
    int r = connect.getResponseCode();
    assertEquals("doPut: Server returned response code " + r, 200, r);
    //get the response of the query
    String response = readResponse(connect.getInputStream());
    assertEquals(response.trim(), "test data /a/b/c");
}

28. RESTServiceTest#doPut()

Project: exist
Source File: RESTServiceTest.java
View license
private void doPut(String data, String path, int responseCode) throws IOException {
    HttpURLConnection connect = getConnection(COLLECTION_URI + '/' + path);
    connect.setRequestProperty("Authorization", "Basic " + credentials);
    connect.setRequestMethod("PUT");
    connect.setDoOutput(true);
    connect.setRequestProperty("ContentType", "application/xquery");
    Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8");
    writer.write(data);
    writer.close();
    connect.connect();
    int r = connect.getResponseCode();
    assertEquals("doPut: Server returned response code " + r, responseCode, r);
}

29. HttpHelper#createConnection()

Project: faunus
Source File: HttpHelper.java
View license
public static HttpURLConnection createConnection(final String uri, final String authValue) throws Exception {
    final URL url = new URL(uri);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(0);
    connection.setReadTimeout(0);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    return connection;
}

30. MoreoverClient#getArticles()

View license
private String getArticles(URL url) throws IOException {
    HttpURLConnection cn = (HttpURLConnection) url.openConnection();
    cn.setRequestMethod("GET");
    cn.addRequestProperty("Content-Type", "text/xml;charset=UTF-8");
    cn.setDoInput(true);
    cn.setDoOutput(false);
    StringWriter writer = new StringWriter();
    IOUtils.copy(new InputStreamReader(cn.getInputStream(), Charset.forName("UTF-8")), writer);
    writer.flush();
    pullTime = new Date().getTime();
    // added after seeing java.net.SocketException: Too many open files
    cn.disconnect();
    return writer.toString();
}

31. IPPPrintService#getIPPConnection()

Project: jdk7u-jdk
Source File: IPPPrintService.java
View license
public static HttpURLConnection getIPPConnection(URL url) {
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) url.openConnection();
    } catch (java.io.IOException ioe) {
        return null;
    }
    if (!(connection instanceof HttpURLConnection)) {
        return null;
    }
    connection.setUseCaches(false);
    connection.setDefaultUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-type", "application/ipp");
    return connection;
}

32. NetUtil#openPostConn()

Project: live-chat-engine
Source File: NetUtil.java
View license
public static HttpURLConnection openPostConn(String url, int connTimeout, int readTimeout) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(connTimeout);
    conn.setReadTimeout(readTimeout);
    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    String agent = System.getProperty("http.agent");
    if (hasText(agent)) {
        conn.setRequestProperty("User-Agent", agent);
    }
    return conn;
}

33. ManyDummyContent#downloadUrl()

Project: mapsforge
Source File: ManyDummyContent.java
View license
// Given a string representation of a URL, sets up a connection and gets
// an input stream.
private InputStreamReader downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    return new InputStreamReader(conn.getInputStream(), "UTF-8");
}

34. ResponseCacheTest#varyMultipleFieldValuesWithMatch()

Project: okhttp
Source File: ResponseCacheTest.java
View license
@Test
public void varyMultipleFieldValuesWithMatch() throws Exception {
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").addHeader("Vary: Accept-Language").setBody("A"));
    server.enqueue(new MockResponse().setBody("B"));
    URL url = server.url("/").url();
    HttpURLConnection multiConnection1 = openConnection(url);
    multiConnection1.setRequestProperty("Accept-Language", "fr-CA, fr-FR");
    multiConnection1.addRequestProperty("Accept-Language", "en-US");
    assertEquals("A", readAscii(multiConnection1));
    HttpURLConnection multiConnection2 = openConnection(url);
    multiConnection2.setRequestProperty("Accept-Language", "fr-CA, fr-FR");
    multiConnection2.addRequestProperty("Accept-Language", "en-US");
    assertEquals("A", readAscii(multiConnection2));
}

35. ResponseCacheTest#varyMultipleFieldValuesWithNoMatch()

Project: okhttp
Source File: ResponseCacheTest.java
View license
@Test
public void varyMultipleFieldValuesWithNoMatch() throws Exception {
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").addHeader("Vary: Accept-Language").setBody("A"));
    server.enqueue(new MockResponse().setBody("B"));
    URL url = server.url("/").url();
    HttpURLConnection multiConnection = openConnection(url);
    multiConnection.setRequestProperty("Accept-Language", "fr-CA, fr-FR");
    multiConnection.addRequestProperty("Accept-Language", "en-US");
    assertEquals("A", readAscii(multiConnection));
    HttpURLConnection notFrenchConnection = openConnection(url);
    notFrenchConnection.setRequestProperty("Accept-Language", "fr-CA");
    notFrenchConnection.addRequestProperty("Accept-Language", "en-US");
    assertEquals("B", readAscii(notFrenchConnection));
}

36. BasicBatchITCase#getConnection()

Project: olingo-odata4
Source File: BasicBatchITCase.java
View license
private HttpURLConnection getConnection(final String content) throws MalformedURLException, IOException, ProtocolException {
    final URL url = new URL(SERVICE_URI + "$batch");
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.POST.toString());
    connection.setRequestProperty(HttpHeader.CONTENT_TYPE, CONTENT_TYPE_HEADER_VALUE);
    connection.setRequestProperty(HttpHeader.ACCEPT, ACCEPT_HEADER_VALUE);
    connection.setDoOutput(true);
    final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.append(content);
    writer.close();
    connection.connect();
    return connection;
}

37. IPPPrintService#getIPPConnection()

Project: openjdk
Source File: IPPPrintService.java
View license
public static HttpURLConnection getIPPConnection(URL url) {
    HttpURLConnection connection;
    URLConnection urlc;
    try {
        urlc = url.openConnection();
    } catch (java.io.IOException ioe) {
        return null;
    }
    if (!(urlc instanceof HttpURLConnection)) {
        return null;
    }
    connection = (HttpURLConnection) urlc;
    connection.setUseCaches(false);
    connection.setDefaultUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-type", "application/ipp");
    return connection;
}

38. DynamicMetadataResolverAdapter#getResourceInputStream()

View license
@Override
protected InputStream getResourceInputStream(final Resource resource, final String entityId) throws IOException {
    final String encodedId = URLEncoder.encode(entityId, "UTF-8");
    final URL url = new URL(resource.getURL().toExternalForm().concat(encodedId));
    final HttpURLConnection httpcon = (HttpURLConnection) (url.openConnection());
    httpcon.setDoOutput(true);
    httpcon.addRequestProperty("Accept", "*/*");
    httpcon.setRequestMethod("GET");
    httpcon.connect();
    return httpcon.getInputStream();
}

39. DynamicMetadataResolverAdapter#getResourceInputStream()

View license
@Override
protected InputStream getResourceInputStream(final Resource resource, final String entityId) throws IOException {
    final String encodedId = EncodingUtils.urlEncode(entityId);
    final URL url = new URL(resource.getURL().toExternalForm().concat(encodedId));
    final HttpURLConnection httpcon = (HttpURLConnection) (url.openConnection());
    httpcon.setDoOutput(true);
    httpcon.addRequestProperty("Accept", "*/*");
    httpcon.setRequestMethod("GET");
    httpcon.connect();
    return httpcon.getInputStream();
}

40. RESTClient#createEntry()

Project: railo
Source File: RESTClient.java
View license
/*private Object listCachesRaw() throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		Object obj;
        conn.setRequestMethod("GET");
        try{
        	obj = getContent(conn);
        }
        finally{
        	disconnectEL(conn);
        }
        return obj;
	}*/
/*private Object featuresRaw() throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		Object obj;
        conn.setRequestMethod("OPTIONS");
        try{
        	obj = getContent(conn);
        }
        finally{
        	disconnectEL(conn);
        }
        return obj;
	}*/
/*private void createCache(String cacheName) throws IOException {
		HttpURLConnection urlConnection = (HttpURLConnection) toURL(cacheName).openConnection();
        urlConnection.setRequestMethod("PUT");

        urlConnection.getResponseCode();
        urlConnection.disconnect();
	}*/
private void createEntry(String cacheName, String key, String value) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) toURL(cacheName, key).openConnection();
    connection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
    connection.setDoOutput(true);
    connection.setRequestMethod("PUT");
    connection.connect();
    // Write the message to the servlet
    // returns
    OutputStream os = connection.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(value);
    oos.flush();
    connection.disconnect();
}

41. FaultTestUtils#getHttpURLConnection()

Project: sandesha
Source File: FaultTestUtils.java
View license
/** 
	 * Sets up a connection to an HTTP endpoint
	 * @return
	 */
public static HttpURLConnection getHttpURLConnection(String uri, String soapAction, boolean soap12) throws Exception {
    // Open a connection to the endpoint
    URL endPointURL = new URL(uri);
    HttpURLConnection connection = (HttpURLConnection) endPointURL.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.addRequestProperty("SOAPAction", soapAction);
    if (soap12) {
        connection.setRequestProperty("Content-Type", "application/soap+xml");
    } else {
        connection.setRequestProperty("Content-Type", "text/xml");
    }
    connection.connect();
    return connection;
}

42. HurlStack#openConnection()

Project: android_tv_metro
Source File: HurlStack.java
View license
/**
     * Opens an [email protected] HttpURLConnection} with parameters.
     * @param url
     * @return an open connection
     * @throws IOException
     */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

43. StreamHandlerTest#testStreamCreate()

Project: cdap
Source File: StreamHandlerTest.java
View license
@Test
public void testStreamCreate() throws Exception {
    // Try to get info on a non-existent stream
    HttpURLConnection urlConn = openURL(createStreamInfoURL("test_stream1"), HttpMethod.GET);
    Assert.assertEquals(HttpResponseStatus.NOT_FOUND.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();
    // try to POST info to the non-existent stream
    urlConn = openURL(createURL("streams/non_existent_stream"), HttpMethod.POST);
    Assert.assertEquals(HttpResponseStatus.NOT_FOUND.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();
    // Now, create the new stream.
    urlConn = openURL(createURL("streams/test_stream1"), HttpMethod.PUT);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();
    // getInfo should now return 200
    urlConn = openURL(createStreamInfoURL("test_stream1"), HttpMethod.GET);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();
}

44. HurlStack#openConnection()

Project: Clover
Source File: HurlStack.java
View license
/**
     * Opens an [email protected] HttpURLConnection} with parameters.
     * @param url
     * @return an open connection
     * @throws IOException
     */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

45. HurlStack#openConnection()

Project: CrossBow
Source File: HurlStack.java
View license
/**
     * Opens an [email protected] HttpURLConnection} with parameters.
     * @param url
     * @return an open connection
     * @throws IOException
     */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

46. GeoUtils#getDocumentFromUrl()

Project: droidar
Source File: GeoUtils.java
View license
@Deprecated
private Document getDocumentFromUrl(String url) throws IOException, MalformedURLException, ProtocolException, FactoryConfigurationError, ParserConfigurationException, SAXException {
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.connect();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    // get the kml file. And parse it to get the coordinates(direction
    // route):
    Document doc = db.parse(urlConnection.getInputStream());
    return doc;
}

47. RESTServiceTest#requestModule()

Project: exist
Source File: RESTServiceTest.java
View license
@Test
public void requestModule() throws IOException {
    String uri = COLLECTION_URI + "?_query=request:get-uri()&_wrap=no";
    HttpURLConnection connect = getConnection(uri);
    connect.setRequestMethod("GET");
    connect.connect();
    int r = connect.getResponseCode();
    assertEquals("Server returned response code " + r, 200, r);
    String response = readResponse(connect.getInputStream()).trim();
    assertTrue(response.endsWith(XmldbURI.ROOT_COLLECTION + "/test"));
    uri = COLLECTION_URI + "?_query=request:get-url()&_wrap=no";
    connect = getConnection(uri);
    connect.setRequestMethod("GET");
    connect.connect();
    r = connect.getResponseCode();
    assertEquals("Server returned response code " + r, 200, r);
    response = readResponse(connect.getInputStream()).trim();
    //TODO : the server name may have been renamed by the Web server
    assertTrue(response.endsWith(XmldbURI.ROOT_COLLECTION + "/test"));
}

48. RESTServiceTest#preparePost()

Project: exist
Source File: RESTServiceTest.java
View license
private HttpURLConnection preparePost(String content, String path) throws IOException {
    HttpURLConnection connect = getConnection(path);
    connect.setRequestProperty("Authorization", "Basic " + credentials);
    connect.setRequestMethod("POST");
    connect.setDoOutput(true);
    connect.setRequestProperty("Content-Type", "application/xml");
    Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8");
    writer.write(content);
    writer.close();
    return connect;
}

49. MoreoverClient#getArticles2()

View license
private String getArticles2(URL url) throws IOException {
    HttpURLConnection cn = (HttpURLConnection) url.openConnection();
    cn.setRequestMethod("GET");
    cn.addRequestProperty("Content-Type", "text/xml;charset=UTF-8");
    cn.setDoInput(true);
    cn.setDoOutput(false);
    BufferedReader reader = new BufferedReader(new InputStreamReader(cn.getInputStream(), Charset.forName("UTF-8")));
    String line = null;
    StringBuilder builder = new StringBuilder();
    String s = "";
    String result = new String(s.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"));
    while ((line = reader.readLine()) != null) {
        result += line;
    }
    pullTime = new Date().getTime();
    return result;
}

50. HurlStack#openConnection()

Project: iosched
Source File: HurlStack.java
View license
/**
     * Opens an [email protected] HttpURLConnection} with parameters.
     * @param url
     * @return an open connection
     * @throws IOException
     */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

51. HttpConnectStack#openConnection()

View license
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol())) {
        if (mSslSocketFactory != null) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
        } else {
            //??????
            HTTPSTrustManager.allowAllSSL();
        }
    }
    return connection;
}

52. HurlStack#openConnection()

View license
/**
     * Opens an [email protected] HttpURLConnection} with parameters.
     * @param url
     * @return an open connection
     * @throws IOException
     */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

53. WebDAVSynchronizer#createConnection()

View license
private HttpURLConnection createConnection(String url) {
    URL newUrl = null;
    try {
        newUrl = new URL(url);
    } catch (MalformedURLException e) {
        return null;
    }
    HttpURLConnection con = null;
    try {
        con = (HttpURLConnection) newUrl.openConnection();
    } catch (IOException e) {
        return null;
    }
    con.setReadTimeout(60000);
    con.setConnectTimeout(60000);
    con.addRequestProperty("Expect", "100-continue");
    con.addRequestProperty("Authorization", "Basic " + Base64.encodeToString((this.username + ":" + this.password).getBytes(), Base64.NO_WRAP));
    return con;
}

54. HttpServerTest#tesFormParamWithURLEncoded()

Project: msf4j
Source File: HttpServerTest.java
View license
@Test
public void tesFormParamWithURLEncoded() throws IOException {
    HttpURLConnection connection = request("/test/v1/formParam", HttpMethod.POST);
    String rawData = "name=wso2&age=10";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }
    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");
}

55. HttpServerTest#tesFormParamWithURLEncodedList()

Project: msf4j
Source File: HttpServerTest.java
View license
@Test
public void tesFormParamWithURLEncodedList() throws IOException {
    HttpURLConnection connection = request("/test/v1/formParamWithList", HttpMethod.POST);
    String rawData = "names=WSO2&names=IBM";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }
    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "2");
}

56. HttpServerTest#testGetAllFormItemsWithURLEncoded()

Project: msf4j
Source File: HttpServerTest.java
View license
@Test
public void testGetAllFormItemsWithURLEncoded() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/getAllFormItemsURLEncoded", HttpMethod.POST);
    String rawData = "names=WSO2&names=IBM&age=10&type=Software";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }
    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals("No of Companies-2 type-Software", response);
}

57. MockWebServerTest#disconnectRequestHalfway()

Project: okhttp
Source File: MockWebServerTest.java
View license
@Test
public void disconnectRequestHalfway() throws IOException {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_DURING_REQUEST_BODY));
    // Limit the size of the request body that the server holds in memory to an arbitrary
    // 3.5 MBytes so this test can pass on devices with little memory.
    server.setBodyLimit(7 * 512 * 1024);
    HttpURLConnection connection = (HttpURLConnection) server.url("/").url().openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    // 1 GB
    connection.setFixedLengthStreamingMode(1024 * 1024 * 1024);
    connection.connect();
    OutputStream out = connection.getOutputStream();
    byte[] data = new byte[1024 * 1024];
    int i;
    for (i = 0; i < 1024; i++) {
        try {
            out.write(data);
            out.flush();
        } catch (IOException e) {
            break;
        }
    }
    // Halfway +/- 1%
    assertEquals(512f, i, 10f);
}

58. BasicHttpITCase#testODataMaxVersion()

Project: olingo-odata4
Source File: BasicHttpITCase.java
View license
@Test
public void testODataMaxVersion() throws Exception {
    URL url = new URL(SERVICE_URI);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ODATA_MAX_VERSION, "4.0");
    connection.setRequestProperty(HttpHeader.ACCEPT, "*/*");
    connection.connect();
    assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
    assertEquals("4.0", connection.getHeaderField(HttpHeader.ODATA_VERSION));
}

59. TestJsonRestServlet#invoke()

Project: oozie
Source File: TestJsonRestServlet.java
View license
private int invoke(String method, String resource, String queryString, String contentType) throws Exception {
    String s = container.getServletURL("/dummy");
    if (resource != null) {
        s += resource;
    }
    if (queryString != null) {
        s += "?" + queryString;
    }
    HttpURLConnection conn = (HttpURLConnection) new URL(s).openConnection();
    conn.setRequestProperty("content-type", contentType);
    conn.setRequestMethod(method);
    conn.connect();
    return conn.getResponseCode();
}

60. HurlStack#openConnection()

Project: SimplifyReader
Source File: HurlStack.java
View license
/**
     * Opens an [email protected] java.net.HttpURLConnection} with parameters.
     * @param url
     * @return an open connection
     * @throws java.io.IOException
     */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

61. TeleporterHttpClient#getHttpGetStatus()

Project: sling
Source File: TeleporterHttpClient.java
View license
public int getHttpGetStatus(String url) throws MalformedURLException, IOException {
    final HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
    setConnectionCredentials(c);
    c.setUseCaches(false);
    c.setDoOutput(true);
    c.setDoInput(true);
    c.setInstanceFollowRedirects(false);
    boolean gotStatus = false;
    int result = 0;
    try {
        result = c.getResponseCode();
        gotStatus = true;
    } finally {
        // If we didn't get a status, do not attempt
        // to get input streams as this would retry connecting
        cleanup(c, gotStatus);
    }
    return result;
}

62. MoreoverClient#getArticles2()

Project: streams
Source File: MoreoverClient.java
View license
private String getArticles2(URL url) throws IOException {
    HttpURLConnection cn = (HttpURLConnection) url.openConnection();
    cn.setRequestMethod("GET");
    cn.addRequestProperty("Content-Type", "text/xml;charset=UTF-8");
    cn.setDoInput(true);
    cn.setDoOutput(false);
    BufferedReader reader = new BufferedReader(new InputStreamReader(cn.getInputStream(), Charset.forName("UTF-8")));
    String line = null;
    StringBuilder builder = new StringBuilder();
    String s = "";
    String result = new String(s.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"));
    while ((line = reader.readLine()) != null) {
        result += line;
    }
    pullTime = new Date().getTime();
    return result;
}

63. MoreoverClient#getArticles()

Project: streams
Source File: MoreoverClient.java
View license
private String getArticles(URL url) throws IOException {
    HttpURLConnection cn = (HttpURLConnection) url.openConnection();
    cn.setRequestMethod("GET");
    cn.addRequestProperty("Content-Type", "text/xml;charset=UTF-8");
    cn.setDoInput(true);
    cn.setDoOutput(false);
    StringWriter writer = new StringWriter();
    IOUtils.copy(new InputStreamReader(cn.getInputStream(), Charset.forName("UTF-8")), writer);
    writer.flush();
    pullTime = new Date().getTime();
    return writer.toString();
}

64. WebClient#get()

Project: ThriftyPaxos
Source File: WebClient.java
View license
/**
     * Open an URL and get the HTML data.
     *
     * @param url the HTTP URL
     * @return the HTML as a string
     */
String get(String url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod("GET");
    conn.setInstanceFollowRedirects(true);
    if (acceptLanguage != null) {
        conn.setRequestProperty("accept-language", acceptLanguage);
    }
    conn.connect();
    int code = conn.getResponseCode();
    contentType = conn.getContentType();
    if (code != HttpURLConnection.HTTP_OK) {
        throw new IOException("Result code: " + code);
    }
    InputStream in = conn.getInputStream();
    String result = IOUtils.readStringAndClose(new InputStreamReader(in), -1);
    conn.disconnect();
    return result;
}

65. HurlStack#openConnection()

Project: TitanjumNote
Source File: HurlStack.java
View license
/**
     * Opens an [email protected] HttpURLConnection} with parameters.
     * @param url
     * @return an open connection
     * @throws IOException
     */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

66. HurlStack#openConnection()

Project: volley
Source File: HurlStack.java
View license
/**
     * Opens an [email protected] HttpURLConnection} with parameters.
     * @param url
     * @return an open connection
     * @throws IOException
     */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(CONNECTION_TIME_OUT_MS);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

67. HurlStack#openConnection()

Project: WayHoo
Source File: HurlStack.java
View license
/**
     * Opens an [email protected] HttpURLConnection} with parameters.
     * @param url
     * @return an open connection
     * @throws IOException
     */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

68. HttpClient#httpPostCompressed()

Project: webbit
Source File: HttpClient.java
View license
public static URLConnection httpPostCompressed(WebServer webServer, String path, String body) throws IOException {
    URL url = new URL(webServer.getUri().toURL(), path);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.addRequestProperty("Content-Encoding", "gzip");
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    urlConnection.setDoOutput(true);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(baos);
    gzip.write(body.getBytes(Charset.forName("UTF8")));
    gzip.close();
    urlConnection.getOutputStream().write(baos.toByteArray());
    return urlConnection;
}

69. WPDelayedHurlStack#openConnection()

View license
/**
     * Opens an [email protected] HttpURLConnection} with parameters.
     * @param url
     * @return an open connection
     * @throws IOException
     */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

70. ESMetricsAccessorTest#loadTestData()

Project: apiman
Source File: ESMetricsAccessorTest.java
View license
private static void loadTestData() throws Exception {
    String url = "http://localhost:6500/_bulk";
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    OutputStream os = conn.getOutputStream();
    InputStream is = ESMetricsAccessorTest.class.getResourceAsStream("bulk-metrics-data.txt");
    IOUtils.copy(is, os);
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);
    if (conn.getResponseCode() > 299) {
        IOUtils.copy(conn.getInputStream(), System.err);
        throw new IOException("Bulk load of data failed with: " + conn.getResponseMessage());
    }
    client.execute(new Refresh.Builder().addIndex("apiman_metrics").refresh(true).build());
}

71. HttpHelper#sendRequestAndGetResponseCookie()

View license
public static CookiesContainer sendRequestAndGetResponseCookie(String... requestFormattedCookies) throws Exception {
    HttpURLConnection con = (HttpURLConnection) (new URL("http://localhost:1234")).openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", TEST_USER_AGENT);
    for (String requestFormattedCookie : requestFormattedCookies) {
        con.setRequestProperty("Cookie", requestFormattedCookie);
    }
    con.getResponseCode();
    List<String> responseCookies = con.getHeaderFields().get("Set-Cookie");
    CookiesContainer cookiesContainer = getCookiesContainer(responseCookies);
    return cookiesContainer;
}

72. BaseHiveExploreServiceTest#setStreamProperties()

View license
protected static void setStreamProperties(String namespace, String streamName, StreamProperties properties) throws IOException {
    int port = streamHttpService.getBindAddress().getPort();
    URL url = new URL(String.format("http://127.0.0.1:%d%s/namespaces/%s/streams/%s/properties", port, Constants.Gateway.API_VERSION_3, namespace, streamName));
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    urlConn.setRequestMethod(HttpMethod.PUT);
    urlConn.setDoOutput(true);
    urlConn.getOutputStream().write(GSON.toJson(properties).getBytes(Charsets.UTF_8));
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();
}

73. BaseHiveExploreServiceTest#sendStreamEvent()

View license
protected static void sendStreamEvent(Id.Stream streamId, Map<String, String> headers, byte[] body) throws IOException {
    HttpURLConnection urlConn = openStreamConnection(streamId);
    urlConn.setRequestMethod(HttpMethod.POST);
    urlConn.setDoOutput(true);
    for (Map.Entry<String, String> header : headers.entrySet()) {
        // headers must be prefixed by the stream name, otherwise they are filtered out by the StreamHandler.
        // the handler also strips the stream name from the key before writing it to the stream.
        urlConn.addRequestProperty(streamId.getId() + "." + header.getKey(), header.getValue());
    }
    urlConn.getOutputStream().write(body);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();
}

74. NettyRouterPipelineAuthTest#testGet()

View license
private void testGet(int expectedStatus, String expectedResponse, String path, Map<String, String> headers) throws Exception {
    URL url = new URL("http", HOSTNAME, ROUTER.getServiceMap().get(GATEWAY_NAME), path);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoInput(true);
    for (Map.Entry<String, String> header : headers.entrySet()) {
        connection.setRequestProperty(header.getKey(), header.getValue());
    }
    connection.connect();
    try {
        Assert.assertEquals(expectedStatus, connection.getResponseCode());
        if (expectedResponse != null) {
            byte[] content = ByteStreams.toByteArray(connection.getInputStream());
            Assert.assertEquals(expectedResponse, Bytes.toString(content));
        }
    } finally {
        connection.disconnect();
    }
}

75. RoutingToDataSetsTest#doRequest()

Project: cdap
Source File: RoutingToDataSetsTest.java
View license
private String doRequest(String resource, String requestMethod) throws Exception {
    resource = String.format("http://localhost:%d%s" + resource, port, Constants.Gateway.API_VERSION_3);
    URL url = new URL(resource);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(requestMethod);
    conn.setDoInput(true);
    conn.connect();
    try {
        byte[] responseBody = null;
        if (HttpURLConnection.HTTP_OK == conn.getResponseCode() && conn.getDoInput()) {
            InputStream is = conn.getInputStream();
            try {
                responseBody = ByteStreams.toByteArray(is);
            } finally {
                is.close();
            }
        }
        return new String(responseBody, Charsets.UTF_8);
    } finally {
        conn.disconnect();
    }
}

76. Configs#createConnection()

Project: datacollector
Source File: Configs.java
View license
@VisibleForTesting
public HttpURLConnection createConnection(String hostPort, String path) throws IOException {
    String scheme = (sslEnabled) ? "https://" : "http://";
    URL url = new URL(scheme + hostPort.trim() + path);
    HttpURLConnection conn = createConnection(url);
    conn.setConnectTimeout(connectionTimeOutMs);
    conn.setReadTimeout(readTimeOutMs);
    if (sslEnabled) {
        HttpsURLConnection sslConn = (HttpsURLConnection) conn;
        sslConn.setSSLSocketFactory(sslSocketFactory);
        if (!hostVerification) {
            sslConn.setHostnameVerifier(ACCEPT_ALL_HOSTNAME_VERIFIER);
        }
    }
    conn.setRequestProperty(Constants.X_SDC_APPLICATION_ID_HEADER, appId);
    return conn;
}

77. SimpleHttpTest#httpPost()

View license
@Test
public void httpPost() throws IOException {
    InetSocketTransportAddress httpAddress = findHttpAddress(client());
    if (httpAddress == null) {
        throw new IllegalArgumentException("no HTTP address found");
    }
    URL base = new URL("http://" + httpAddress.getHost() + ":" + httpAddress.getPort());
    URL url = new URL(base, "_langdetect");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    Streams.copy(new StringReader("Das ist ein Text"), new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
    StringWriter response = new StringWriter();
    Streams.copy(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8), response);
    assertEquals("{\"languages\":[{\"language\":\"de\",\"probability\":0.9999967609942226}]}", response.toString());
}

78. SimpleHttpTest#httpPostShortProfile()

View license
@Test
public void httpPostShortProfile() throws IOException {
    InetSocketTransportAddress httpAddress = findHttpAddress(client());
    if (httpAddress == null) {
        throw new IllegalArgumentException("no HTTP address found");
    }
    URL base = new URL("http://" + httpAddress.getHost() + ":" + httpAddress.getPort());
    URL url = new URL(base, "_langdetect?profile=short-text");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    Streams.copy(new StringReader("Das ist ein Text"), new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
    StringWriter response = new StringWriter();
    Streams.copy(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8), response);
    assertEquals("{\"profile\":\"short-text\",\"languages\":[{\"language\":\"de\",\"probability\":0.9999968539079941}]}", response.toString());
}

79. Main#put()

Project: enunciate
Source File: Main.java
View license
private static void put(String uri, String mediaType, InputStream in) throws IOException {
    URL u = new URL(uri);
    HttpURLConnection uc = (HttpURLConnection) u.openConnection();
    uc.setRequestMethod("PUT");
    uc.setRequestProperty("Content-Type", mediaType);
    uc.setDoOutput(true);
    OutputStream out = uc.getOutputStream();
    byte[] data = new byte[2048];
    int read;
    while ((read = in.read(data)) != -1) out.write(data, 0, read);
    out.close();
    int status = uc.getResponseCode();
    System.out.println("Status: " + status);
}

80. Main#post()

Project: enunciate
Source File: Main.java
View license
private static void post(String uri, String mediaType, InputStream in) throws IOException {
    URL u = new URL(uri);
    HttpURLConnection uc = (HttpURLConnection) u.openConnection();
    uc.setRequestMethod("POST");
    uc.setRequestProperty("Content-Type", mediaType);
    uc.setDoOutput(true);
    OutputStream out = uc.getOutputStream();
    byte[] data = new byte[2048];
    int read;
    while ((read = in.read(data)) != -1) out.write(data, 0, read);
    out.close();
    int status = uc.getResponseCode();
    System.out.println("Status: " + status);
}

81. Main#put()

Project: enunciate
Source File: Main.java
View license
private static void put(String uri, String mediaType, InputStream in) throws IOException {
    URL u = new URL(uri);
    HttpURLConnection uc = (HttpURLConnection) u.openConnection();
    uc.setRequestMethod("PUT");
    uc.setRequestProperty("Content-Type", mediaType);
    uc.setDoOutput(true);
    OutputStream out = uc.getOutputStream();
    byte[] data = new byte[2048];
    int read;
    while ((read = in.read(data)) != -1) out.write(data, 0, read);
    out.close();
    int status = uc.getResponseCode();
    System.out.println("Status: " + status);
}

82. Main#post()

Project: enunciate
Source File: Main.java
View license
private static void post(String uri, String mediaType, InputStream in) throws IOException {
    URL u = new URL(uri);
    HttpURLConnection uc = (HttpURLConnection) u.openConnection();
    uc.setRequestMethod("POST");
    uc.setRequestProperty("Content-Type", mediaType);
    uc.setDoOutput(true);
    OutputStream out = uc.getOutputStream();
    byte[] data = new byte[2048];
    int read;
    while ((read = in.read(data)) != -1) out.write(data, 0, read);
    out.close();
    int status = uc.getResponseCode();
    System.out.println("Status: " + status);
}

83. PostExample#doPost()

Project: exist
Source File: PostExample.java
View license
private void doPost(String request) throws IOException {
    URL url = new URL("http://localhost:8080/exist/rest" + XmldbURI.ROOT_COLLECTION);
    HttpURLConnection connect = (HttpURLConnection) url.openConnection();
    connect.setRequestMethod("POST");
    connect.setDoOutput(true);
    OutputStream os = connect.getOutputStream();
    os.write(request.getBytes(UTF_8));
    connect.connect();
    BufferedReader is = new BufferedReader(new InputStreamReader(connect.getInputStream()));
    String line;
    while ((line = is.readLine()) != null) System.out.println(line);
}

84. RESTServiceTest#xqueryGetWithEmptyPath()

Project: exist
Source File: RESTServiceTest.java
View license
@Test
public void xqueryGetWithEmptyPath() throws IOException {
    /* store the documents that we need for this test */
    doPut(TEST_XQUERY_WITH_PATH_PARAMETER, "requestwithpath.xq", 201);
    String path = COLLECTION_URI + "/requestwithpath.xq";
    HttpURLConnection connect = getConnection(path);
    connect.setRequestProperty("Authorization", "Basic " + credentials);
    connect.setRequestMethod("GET");
    connect.connect();
    int r = connect.getResponseCode();
    assertEquals("Server returned response code " + r, 200, r);
    String response = readResponse(connect.getInputStream());
    String pathInfo = response.substring("pathInfo=".length(), response.indexOf("servletPath=") - 2);
    String servletPath = response.substring(response.indexOf("servletPath=") + "servletPath=".length(), response.lastIndexOf("\r\n"));
    //check the responses    
    assertEquals("XQuery servletPath is: \"" + servletPath + "\" expected: \"/db/test/requestwithpath.xq\"", "/db/test/requestwithpath.xq", servletPath);
    assertEquals("XQuery pathInfo is: \"" + pathInfo + "\" expected: \"\"", "", pathInfo);
}

85. RESTServiceTest#xqueryGetWithNonEmptyPath()

Project: exist
Source File: RESTServiceTest.java
View license
@Test
public void xqueryGetWithNonEmptyPath() throws IOException {
    /* store the documents that we need for this test */
    doPut(TEST_XQUERY_WITH_PATH_PARAMETER, "requestwithpath.xq", 201);
    String path = COLLECTION_URI + "/requestwithpath.xq/some/path";
    HttpURLConnection connect = getConnection(path);
    connect.setRequestProperty("Authorization", "Basic " + credentials);
    connect.setRequestMethod("GET");
    connect.connect();
    int r = connect.getResponseCode();
    assertEquals("Server returned response code " + r, 200, r);
    String response = readResponse(connect.getInputStream());
    String pathInfo = response.substring("pathInfo=".length(), response.indexOf("servletPath=") - 2);
    String servletPath = response.substring(response.indexOf("servletPath=") + "servletPath=".length(), response.lastIndexOf("\r\n"));
    //check the responses        
    assertEquals("XQuery servletPath is: \"" + servletPath + "\" expected: \"/db/test/requestwithpath.xq\"", "/db/test/requestwithpath.xq", servletPath);
    assertEquals("XQuery pathInfo is: \"" + pathInfo + "\" expected: \"/some/path\"", "/some/path", pathInfo);
}

86. RESTServiceTest#deleteAgainstXQuery()

Project: exist
Source File: RESTServiceTest.java
View license
@Test
public void deleteAgainstXQuery() throws IOException {
    doPut(TEST_XQUERY_WITH_PATH_PARAMETER, "requestwithcontent.xq", 201);
    String path = COLLECTION_URI_REDIRECTED + "/requestwithcontent.xq/a/b/c";
    HttpURLConnection connect = getConnection(path);
    connect.setRequestProperty("Authorization", "Basic " + credentials);
    connect.setRequestMethod("DELETE");
    connect.connect();
    int r = connect.getResponseCode();
    assertEquals("doDelete: Server returned response code " + r, 200, r);
    //get the response of the query
    String response = readResponse(connect.getInputStream());
    String pathInfo = response.substring("pathInfo=".length(), response.indexOf("servletPath=") - 2);
    assertEquals(pathInfo, "/a/b/c");
}

87. RESTServiceTest#headAgainstXQuery()

Project: exist
Source File: RESTServiceTest.java
View license
@Test
public void headAgainstXQuery() throws IOException {
    doPut(TEST_XQUERY_WITH_PATH_PARAMETER, "requestwithcontent.xq", 201);
    String path = COLLECTION_URI_REDIRECTED + "/requestwithcontent.xq/a/b/c";
    HttpURLConnection connect = getConnection(path);
    connect.setRequestProperty("Authorization", "Basic " + credentials);
    connect.setRequestMethod("HEAD");
    connect.connect();
    int r = connect.getResponseCode();
    assertEquals("doHead: Server returned response code " + r, 200, r);
}

88. CrowdinDownload#exportLocalizations()

Project: ForgeGradle
Source File: CrowdinDownload.java
View license
private void exportLocalizations(String projectId, String key) throws IOException {
    getLogger().debug("Exporting crowdin localizations.");
    URL url = new URL(String.format(EXPORT_URL, projectId, key));
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestProperty("User-Agent", Constants.USER_AGENT);
    con.setInstanceFollowRedirects(true);
    try {
        con.connect();
    } catch (Throwable e) {
        Throwables.propagate(e);
    }
    int reponse = con.getResponseCode();
    con.disconnect();
    if (reponse == 401)
        throw new RuntimeException("Invalid Crowdin API-Key!");
}

89. Caller#openPostConnection()

Project: frostwire-android
Source File: Caller.java
View license
/**
     * @param method
     * @param params
     * @return
     * @throws IOException
     */
private HttpURLConnection openPostConnection(final String method, final Map<String, String> params) throws IOException {
    final HttpURLConnection urlConnection = openConnection(apiRootUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(true);
    final OutputStream outputStream = urlConnection.getOutputStream();
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
    final String post = buildPostBody(method, params);
    writer.write(post);
    writer.close();
    return urlConnection;
}

90. ResumableHttpUploadTask#getNextStartByteFromServer()

View license
/**
   * Makes an HTTP request to determine the range of bytes for this upload that
   * the server has already received. The index of the first byte not yet
   * received by the server is returned.  This method ignores several possible
   * server errors and returns <code>0</code> in those cases.  If the server
   * errors persist, they can be appropriately handled in the [email protected] #upload()}
   * method (where this method should be called from).
   *
   * @return the index of the first byte not yet received by the server for this
   *     upload
   * @throws IOException if the HTTP request cannot be made
   */
private long getNextStartByteFromServer() throws IOException {
    HttpURLConnection connection = urlConnectionFactory.create(uploader.getUrl());
    connection.setRequestMethod(uploader.getHttpRequestMethod().toString());
    connection.setRequestProperty(CONTENT_LENGTH_HEADER_NAME, "0");
    connection.connect();
    if (connection.getResponseCode() != 308) {
        return 0L;
    }
    return getNextByteIndexFromRangeHeader(connection.getHeaderField("Range"));
}

91. HttpUtils#connect()

Project: geogig
Source File: HttpUtils.java
View license
/**
     * Connects to the given URL using HTTP GET method
     */
public static HttpURLConnection connect(String url) throws IOException {
    HttpURLConnection connection;
    connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);
    // connection.addRequestProperty("Accept-Encoding", "gzip");
    LOGGER.debug("Connecting to '{}'...", url);
    connection.connect();
    int responseCode = connection.getResponseCode();
    LOGGER.debug(" connected ({}).", responseCode);
    return connection;
}

92. VersionResponseFilterTest#connect()

View license
private HttpURLConnection connect(final URI uri, final Map<String, List<String>> headers) throws IOException {
    final HttpURLConnection connection;
    connection = (HttpURLConnection) uri.toURL().openConnection();
    connection.setInstanceFollowRedirects(false);
    for (final Map.Entry<String, List<String>> header : headers.entrySet()) {
        for (final String value : header.getValue()) {
            connection.addRequestProperty(header.getKey(), value);
        }
    }
    connection.setRequestMethod("GET");
    connection.getResponseCode();
    return connection;
}

93. MyExperimentClient#doMyExperimentDELETE()

View license
/**
   * Generic method to execute DELETE requests to myExperiment server. This is
   * only to be called when a user is logged in.
   * 
   * @param strURL
   *          The URL on myExperiment to direct DELETE request to.
   * @return An object containing XML Document with server's response body and a
   *         response code. Response body XML document might be null if there
   *         was an error or the user wasn't authorised to perform a certain
   *         action. Response code will always be set.
   * @throws Exception
   */
public ServerResponse doMyExperimentDELETE(String strURL) throws Exception {
    // open server connection using provided URL (with no modifications to it)
    URL url = new URL(strURL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // "tune" the connection
    conn.setRequestMethod("DELETE");
    conn.setRequestProperty("User-Agent", PLUGIN_USER_AGENT);
    conn.setRequestProperty("Authorization", "Basic " + AUTH_STRING);
    // check server's response
    return (doMyExperimentReceiveServerResponse(conn, strURL, true));
}

94. OpenSocialHttpClient#getConnection()

View license
/**
   * Opens a new HTTP connection for the URL associated with this object.
   *
   * @param method
   * @param url
   * @return Opened connection
   * @throws IOException if URL is invalid, or unsupported
   */
private HttpURLConnection getConnection(String method, OpenSocialUrl url, String contentType) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url.toString()).openConnection();
    if (contentType != null && !contentType.equals("")) {
        connection.setRequestProperty(HttpMessage.CONTENT_TYPE, contentType);
    }
    connection.setRequestMethod(method);
    connection.setDoOutput(true);
    connection.connect();
    return connection;
}

95. ResponseCacheTest#varyMatchesChangedRequestHeaderField()

Project: okhttp
Source File: ResponseCacheTest.java
View license
@Test
public void varyMatchesChangedRequestHeaderField() throws Exception {
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").addHeader("Vary: Accept-Language").setBody("A"));
    server.enqueue(new MockResponse().setBody("B"));
    URL url = server.url("/").url();
    HttpURLConnection frenchConnection = openConnection(url);
    frenchConnection.setRequestProperty("Accept-Language", "fr-CA");
    assertEquals("A", readAscii(frenchConnection));
    HttpURLConnection englishConnection = openConnection(url);
    englishConnection.setRequestProperty("Accept-Language", "en-US");
    assertEquals("B", readAscii(englishConnection));
}

96. ResponseCacheTest#varyMatchesUnchangedRequestHeaderField()

Project: okhttp
Source File: ResponseCacheTest.java
View license
@Test
public void varyMatchesUnchangedRequestHeaderField() throws Exception {
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").addHeader("Vary: Accept-Language").setBody("A"));
    server.enqueue(new MockResponse().setBody("B"));
    URL url = server.url("/").url();
    HttpURLConnection frenchConnection1 = openConnection(url);
    frenchConnection1.setRequestProperty("Accept-Language", "fr-CA");
    assertEquals("A", readAscii(frenchConnection1));
    HttpURLConnection frenchConnection2 = openConnection(url);
    frenchConnection2.setRequestProperty("Accept-Language", "fr-CA");
    assertEquals("A", readAscii(frenchConnection2));
}

97. ResponseCacheTest#varyFieldsAreCaseInsensitive()

Project: okhttp
Source File: ResponseCacheTest.java
View license
@Test
public void varyFieldsAreCaseInsensitive() throws Exception {
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").addHeader("Vary: ACCEPT-LANGUAGE").setBody("A"));
    server.enqueue(new MockResponse().setBody("B"));
    URL url = server.url("/").url();
    HttpURLConnection frenchConnection1 = openConnection(url);
    frenchConnection1.setRequestProperty("Accept-Language", "fr-CA");
    assertEquals("A", readAscii(frenchConnection1));
    HttpURLConnection frenchConnection2 = openConnection(url);
    frenchConnection2.setRequestProperty("accept-language", "fr-CA");
    assertEquals("A", readAscii(frenchConnection2));
}

98. ResponseCacheTest#varyAndHttps()

Project: okhttp
Source File: ResponseCacheTest.java
View license
@Test
public void varyAndHttps() throws Exception {
    server.useHttps(sslClient.socketFactory, false);
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").addHeader("Vary: Accept-Language").setBody("A"));
    server.enqueue(new MockResponse().setBody("B"));
    urlFactory.setClient(urlFactory.client().newBuilder().sslSocketFactory(sslClient.socketFactory, sslClient.trustManager).hostnameVerifier(hostnameVerifier).build());
    URL url = server.url("/").url();
    HttpURLConnection connection1 = openConnection(url);
    connection1.setRequestProperty("Accept-Language", "en-US");
    assertEquals("A", readAscii(connection1));
    HttpURLConnection connection2 = openConnection(url);
    connection2.setRequestProperty("Accept-Language", "en-US");
    assertEquals("A", readAscii(connection2));
}

99. DisconnectTest#interruptWritingRequestBody()

Project: okhttp
Source File: DisconnectTest.java
View license
@Test
public void interruptWritingRequestBody() throws Exception {
    // 2 MiB
    int requestBodySize = 2 * 1024 * 1024;
    server.enqueue(new MockResponse().throttleBody(64 * 1024, 125, // 500 Kbps
    TimeUnit.MILLISECONDS));
    server.start();
    HttpURLConnection connection = new OkUrlFactory(client).open(server.url("/").url());
    disconnectLater(connection, 500);
    connection.setDoOutput(true);
    connection.setFixedLengthStreamingMode(requestBodySize);
    OutputStream requestBody = connection.getOutputStream();
    byte[] buffer = new byte[1024];
    try {
        for (int i = 0; i < requestBodySize; i += buffer.length) {
            requestBody.write(buffer);
            requestBody.flush();
        }
        fail("Expected connection to be closed");
    } catch (IOException expected) {
    }
    connection.disconnect();
}

100. ThreadInterruptTest#interruptWritingRequestBody()

Project: okhttp
Source File: ThreadInterruptTest.java
View license
@Test
public void interruptWritingRequestBody() throws Exception {
    // 2 MiB
    int requestBodySize = 2 * 1024 * 1024;
    server.enqueue(new MockResponse().throttleBody(64 * 1024, 125, // 500 Kbps
    TimeUnit.MILLISECONDS));
    server.start();
    interruptLater(500);
    HttpURLConnection connection = new OkUrlFactory(client).open(server.url("/").url());
    connection.setDoOutput(true);
    connection.setFixedLengthStreamingMode(requestBodySize);
    OutputStream requestBody = connection.getOutputStream();
    byte[] buffer = new byte[1024];
    try {
        for (int i = 0; i < requestBodySize; i += buffer.length) {
            requestBody.write(buffer);
            requestBody.flush();
        }
        fail("Expected thread to be interrupted");
    } catch (InterruptedIOException expected) {
    }
    connection.disconnect();
}