Here are the examples of the java api class java.net.HttpURLConnection taken from open source projects.
1. JsonRpcHttpClient#prepareConnection()
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; }
2. RemoteSSOService#getAuthConnection()
View licenseHttpURLConnection 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; }
3. HttpKitExt#downloadMaterial()
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. B6401598#getHttpURLConnection()
View licensestatic 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; }
5. HttpPostMethod#openConnectionInternal()
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; }
6. DefaultStreamWriter#createBatchWriter()
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; } }
7. Downloader#createConnection()
View licensepublic 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; }
8. ITNProxy#post()
View licenseprivate 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; }
9. 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()); }
10. JettyTest#testGzipCompression()
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()); }
11. RESTServiceTest#xqueryGetFailWithNonEmptyPath()
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); }
12. ResponseCacheTest#varyMultipleFieldsWithMatch()
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()
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()
View licensestatic 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. StockQuote#setUpHttpConnection()
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; }
16. HttpURLConnectionHandler#openConnection()
View licenseprivate 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; }
17. HttpClient#init()
View licenseprotected 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; }
18. SimpleConsumerTest#sendMessageByHttp()
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. RESTServiceTest#uploadData()
View licenseprivate 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(); }
20. RESTServiceTest#uploadDataPlus()
View licenseprivate 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(); }
21. RESTServiceTest#putFailAgainstCollection()
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); }
22. RESTServiceTest#putWithCharset()
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(); }
23. RESTServiceTest#putFailAndRechallengeAuthorization()
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); }
24. RESTServiceTest#putAgainstXQuery()
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"); }
25. RESTServiceTest#doPut()
View licenseprivate 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); }
26. HttpHelper#createConnection()
View licensepublic 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; }
27. EC2MetadataClient#readResource()
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); }
28. HtmlFetcher#createUrlConnection()
View licenseprotected 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; }
29. 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(); }
30. ResponseCacheTest#varyMultipleFieldValuesWithMatch()
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)); }
31. ResponseCacheTest#varyMultipleFieldValuesWithNoMatch()
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)); }
32. BasicBatchITCase#getConnection()
View licenseprivate 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; }
33. IPPPrintService#getIPPConnection()
View licensepublic 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; }
34. 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(); }
35. 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(); }
36. IPPPrintService#getIPPConnection()
View licensepublic 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; }
37. NetUtil#openPostConn()
View licensepublic 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; }
38. ManyDummyContent#downloadUrl()
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"); }
39. MoreoverClient#getArticles()
View licenseprivate 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(); }
40. RESTClient#createEntry()
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()
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. WebClient#get()
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; }
43. HurlStack#openConnection()
View license/** * Opens an {@link 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; }
44. HurlStack#openConnection()
View license/** * Opens an {@link 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; }
45. HurlStack#openConnection()
View license/** * Opens an {@link 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. HttpClient#httpPostCompressed()
View licensepublic 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; }
47. WPDelayedHurlStack#openConnection()
View license/** * Opens an {@link 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; }
48. HurlStack#openConnection()
View license/** * Opens an {@link 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; }
49. TeleporterHttpClient#getHttpGetStatus()
View licensepublic 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; }
50. MoreoverClient#getArticles2()
View licenseprivate 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; }
51. MoreoverClient#getArticles()
View licenseprivate 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(); }
52. HurlStack#openConnection()
View license/** * Opens an {@link 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. HurlStack#openConnection()
View license/** * Opens an {@link 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; }
54. GeoUtils#getDocumentFromUrl()
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; }
55. RESTServiceTest#requestModule()
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")); }
56. RESTServiceTest#preparePost()
View licenseprivate 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; }
57. StreamHandlerTest#testStreamCreate()
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(); }
58. HurlStack#openConnection()
View license/** * Opens an {@link 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; }
59. MoreoverClient#getArticles2()
View licenseprivate 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; }
60. HurlStack#openConnection()
View license/** * Opens an {@link 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; }
61. BasicHttpITCase#testODataMaxVersion()
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)); }
62. TestJsonRestServlet#invoke()
View licenseprivate 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(); }
63. HttpConnectStack#openConnection()
View licenseprivate 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; }
64. HurlStack#openConnection()
View license/** * Opens an {@link 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; }
65. WebDAVSynchronizer#createConnection()
View licenseprivate 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; }
66. HttpServerTest#tesFormParamWithURLEncoded()
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"); }
67. HttpServerTest#tesFormParamWithURLEncodedList()
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"); }
68. HttpServerTest#testGetAllFormItemsWithURLEncoded()
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); }
69. MockWebServerTest#disconnectRequestHalfway()
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); }
70. PostExample#doPost()
View licenseprivate 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); }
71. 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; }
72. 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)); }
73. VersionResponseFilterTest#connect()
View licenseprivate 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; }
74. HttpUtils#connect()
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; }
75. 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 {@link #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")); }
76. RoutingToDataSetsTest#doRequest()
View licenseprivate 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(); } }
77. NettyRouterPipelineAuthTest#testGet()
View licenseprivate 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(); } }
78. BaseHiveExploreServiceTest#sendStreamEvent()
View licenseprotected 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(); }
79. BaseHiveExploreServiceTest#setStreamProperties()
View licenseprotected 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(); }
80. HttpHelper#sendRequestAndGetResponseCookie()
View licensepublic 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; }
81. HTTP#doPut()
View licenseprivate static URLConnection doPut(String url, Map<String, ?> headers, String contentType, String charset, String body) throws IOException { HttpURLConnection connection; /* Handle output. */ connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(DEFAULT_TIMEOUT_SECONDS * 1000); connection.setRequestMethod("PUT"); connection.setDoOutput(true); manageContentTypeHeaders(contentType, charset, connection); manageHeaders(headers, connection); if (!(body == null || body.isEmpty())) { IO.write(connection.getOutputStream(), body, IO.DEFAULT_CHARSET); } return connection; }
82. ControllerTest#sendDeleteRequest()
View licensepublic static String sendDeleteRequest(String urlString) throws IOException { final long start = System.currentTimeMillis(); final URL url = new URL(urlString); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("DELETE"); conn.connect(); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); final StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } final long stop = System.currentTimeMillis(); LOGGER.info(" Time take for Request : " + urlString + " in ms:" + (stop - start)); return sb.toString(); }
83. TestJsonRestServlet#invokeAndGetResponse()
View licenseprivate String invokeAndGetResponse(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(); StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = reader.readLine(); while (line != null) { sb.append(line); line = reader.readLine(); } return sb.toString(); }
84. PingITCase#redirect()
View license@Test public void redirect() throws Exception { URL url = new URL(REDIRECT_URI); LOG.debug("redirect request: " + REDIRECT_URI); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "*/*"); connection.connect(); assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); }
85. PingITCase#ping()
View license@Test public void ping() throws Exception { URL url = new URL(SERVICE_URI); LOG.debug("ping request: " + SERVICE_URI); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "*/*"); connection.connect(); assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); }
86. EntityReferenceITCase#testContextURLEntityCollection()
View license@Test public void testContextURLEntityCollection() throws Exception { URL url = new URL(SERVICE_URI + "/ESAllPrim/$ref"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty(HttpHeader.ACCEPT, ContentType.APPLICATION_JSON.toContentTypeString()); connection.setRequestMethod(HttpMethod.GET.name()); connection.connect(); assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content.contains(CONTEXT_COLLECTION_REFERENCE)); }
87. EntityReferenceITCase#testContextURlSingleEntity()
View license@Test public void testContextURlSingleEntity() throws Exception { URL url = new URL(SERVICE_URI + "/ESAllPrim(0)/$ref"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty(HttpHeader.ACCEPT, ContentType.APPLICATION_JSON.toContentTypeString()); connection.setRequestMethod(HttpMethod.GET.name()); connection.connect(); assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content.contains(CONTEXT_ENTITY_REFERENCE)); }
88. BasicHttpITCase#testIEEE754ParameterViaAcceptHeader()
View license@Test public void testIEEE754ParameterViaAcceptHeader() throws Exception { final URL url = new URL(SERVICE_URI + "ESAllPrim(32767)"); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;IEEE754Compatible=true"); connection.connect(); assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.create(ContentType.JSON, ContentType.PARAMETER_IEEE754_COMPATIBLE, "true"), ContentType.create(connection.getContentType())); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content.contains("\"PropertyDecimal\":\"34\"")); assertTrue(content.contains("\"PropertyInt64\":\"9223372036854775807\"")); }
89. BasicHttpITCase#testIEEE754ParameterContentNegotiation()
View license@Test public void testIEEE754ParameterContentNegotiation() throws Exception { final URL url = new URL(SERVICE_URI + "ESAllPrim(32767)?$format=application/json;IEEE754Compatible=true"); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;IEEE754Compatible=false"); connection.connect(); assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.create(ContentType.JSON, ContentType.PARAMETER_IEEE754_COMPATIBLE, "true"), ContentType.create(connection.getContentType())); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content.contains("\"PropertyDecimal\":\"34\"")); assertTrue(content.contains("\"PropertyInt64\":\"9223372036854775807\"")); }
90. BasicHttpITCase#testAcceptCharset()
View license@Test public void testAcceptCharset() throws Exception { URL url = new URL(SERVICE_URI); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;q=0.2;odata.metadata=minimal;charset=utf-8"); connection.connect(); assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.create(ContentType.JSON, ContentType.PARAMETER_CHARSET, "utf-8"), ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE))); }
91. BasicHttpITCase#testAcceptSimple()
View license@Test public void testAcceptSimple() throws Exception { URL url = new URL(SERVICE_URI); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json"); connection.connect(); assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE))); }
92. BasicHttpITCase#testAccept()
View license@Test public void testAccept() throws Exception { URL url = new URL(SERVICE_URI); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;q=0.2;odata.metadata=minimal"); connection.connect(); assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE))); }
93. BasicAsyncITCase#postRequest()
View licenseprivate HttpURLConnection postRequest(final URL url, final String content, final Map<String, String> headers) throws IOException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.POST.toString()); // for (Map.Entry<String, String> header : headers.entrySet()) { connection.setRequestProperty(header.getKey(), header.getValue()); } // connection.setDoOutput(true); final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.append(content); writer.close(); connection.connect(); return connection; }
94. UrlConnectionCacheTest#varyMatchesChangedRequestHeaderField()
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 frConnection = urlFactory.open(url); frConnection.addRequestProperty("Accept-Language", "fr-CA"); assertEquals("A", readAscii(frConnection)); HttpURLConnection enConnection = urlFactory.open(url); enConnection.addRequestProperty("Accept-Language", "en-US"); assertEquals("B", readAscii(enConnection)); }
95. URLConnectionTest#testEarlyDisconnectDoesntHarmPooling()
View licenseprivate void testEarlyDisconnectDoesntHarmPooling(TransferKind transferKind) throws Exception { MockResponse response1 = new MockResponse(); transferKind.setBody(response1, "ABCDEFGHIJK", 1024); server.enqueue(response1); MockResponse response2 = new MockResponse(); transferKind.setBody(response2, "LMNOPQRSTUV", 1024); server.enqueue(response2); HttpURLConnection connection1 = urlFactory.open(server.url("/").url()); InputStream in1 = connection1.getInputStream(); assertEquals("ABCDE", readAscii(in1, 5)); in1.close(); connection1.disconnect(); HttpURLConnection connection2 = urlFactory.open(server.url("/").url()); InputStream in2 = connection2.getInputStream(); assertEquals("LMNOP", readAscii(in2, 5)); in2.close(); connection2.disconnect(); assertEquals(0, server.takeRequest().getSequenceNumber()); // Connection is pooled! assertEquals(1, server.takeRequest().getSequenceNumber()); }
96. ThreadInterruptTest#interruptWritingRequestBody()
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(); }
97. DisconnectTest#interruptWritingRequestBody()
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(); }
98. RESTServiceTest#xqueryGetWithEmptyPath()
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); }
99. RESTServiceTest#xqueryGetWithNonEmptyPath()
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); }
100. Main#post()
View licenseprivate 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); }