Java Code Examples for java.net.URLConnection#getOutputStream()

The following examples show how to use java.net.URLConnection#getOutputStream() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: AthenaServing   File: SslTest.java    License: Apache License 2.0 6 votes vote down vote up
public String postRequest(String urlAddress,String args,int timeOut) throws Exception{
    URL url = new URL(urlAddress);
    if("https".equalsIgnoreCase(url.getProtocol())){
        SslUtils.ignoreSsl();
    }
    URLConnection u = url.openConnection();
    u.setDoInput(true);
    u.setDoOutput(true);
    u.setConnectTimeout(timeOut);
    u.setReadTimeout(timeOut);
    OutputStreamWriter osw = new OutputStreamWriter(u.getOutputStream(), "UTF-8");
    osw.write(args);
    osw.flush();
    osw.close();
    u.getOutputStream();
    return IOUtils.toString(u.getInputStream());
}
 
Example 2
Source Project: appengine-tck   File: URLFetchTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testURLConnection() throws Exception {
    URL fetch = getFetchUrl();
    URLConnection conn = fetch.openConnection();
    Assert.assertTrue(conn instanceof HttpURLConnection);
    HttpURLConnection huc = (HttpURLConnection) conn;
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.addRequestProperty("Content-Type", "application/octet-stream");
    huc.connect();
    try {
        OutputStream out = conn.getOutputStream();
        out.write("Juhuhu".getBytes());
        out.flush();

        String content = new String(FetchServlet.toBytes(conn.getInputStream()));
        Assert.assertEquals("Bruhuhu", content);
        Assert.assertEquals(200, huc.getResponseCode());
    } finally {
        huc.disconnect();
    }
}
 
Example 3
Source Project: quarkus   File: ValidatorTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testManualValidationPassed() throws Exception {
    URLConnection connection = uri.openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "application/json");

    byte[] body = Json.createObjectBuilder()
            .add("name", "Stuart")
            .add("email", "[email protected]")
            .build().toString().getBytes(StandardCharsets.UTF_8);
    try (OutputStream o = connection.getOutputStream()) {
        o.write(body);
    }

    InputStream in = connection.getInputStream();
    byte[] buf = new byte[100];
    int r;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    while ((r = in.read(buf)) > 0) {
        out.write(buf, 0, r);
    }
    Assertions.assertEquals("passed", new String(out.toByteArray(), "UTF-8"));
}
 
Example 4
@Test
public void testRequiredPackagesImported() throws IOException {
  LocalServerReceiver codeReceiver = new LocalServerReceiver();
  String redirectUri = codeReceiver.getRedirectUri();
  URLConnection connection = new URL(redirectUri).openConnection();
  connection.setDoOutput(true);
  try (OutputStream outputStream = connection.getOutputStream();
      InputStreamReader reader = new InputStreamReader(connection.getInputStream())) {
    outputStream.write("hello".getBytes(StandardCharsets.UTF_8));
    StringBuilder response = new StringBuilder();
    char[] buffer = new char[1024];
    while (reader.read(buffer) != -1) {
      response.append(buffer);
    }
    assertThat(response.toString(), containsString("OAuth 2.0 Authentication Token Received"));
  }
}
 
Example 5
private void _postMessZalo(String url, String param) {

		try {
			String charset = "UTF-8";
			URLConnection connection = new URL(url).openConnection();
			connection.setDoOutput(true); // Triggers POST.
			connection.setRequestProperty("Content-Type", "application/json;");

			OutputStream output = connection.getOutputStream();
			output.write(param.getBytes(charset));

			connection.getInputStream();
			_log.info("Send zalo message success");
		}
		catch (Exception e) {
			_log.error(e);
		}
	}
 
Example 6
Source Project: RestServices   File: Misc.java    License: Apache License 2.0 6 votes vote down vote up
public static String retrieveURL(String url, String postdata) throws Exception {
      // Send data, appname
      URLConnection conn = new URL(url).openConnection();

      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      if (postdata != null) {
	try ( 
		OutputStream os = conn.getOutputStream()
	) {
		IOUtils.copy(new ByteArrayInputStream(postdata.getBytes(StandardCharsets.UTF_8)), os);
	}
      }
	
String result;
try (
	InputStream is = conn.getInputStream()
) {
	// Get the response
	result = IOUtils.toString(is, StandardCharsets.UTF_8);
}

      return result;
  }
 
Example 7
Source Project: phoebus   File: XmlRpc.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/** Send XML-RPC command, retrieve response
 *
 *  @param url Server URL
 *  @param command Command to send
 *  @return "value" from the reply
 *  @throws Exception on error
 */
public static Element communicate(final URL url, final String command) throws Exception
{
    final URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    final OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
    out.write(command);
    out.flush();
    out.close();

    // Expect <methodResponse><params><param><value>
    Element el = XMLUtil.openXMLDocument(connection.getInputStream(), "methodResponse");
    el = getChildElement(el, "params");
    el = getChildElement(el, "param");
    el = getChildElement(el, "value");
   return el;
}
 
Example 8
Source Project: micro-integrator   File: JSONClient.java    License: Apache License 2.0 5 votes vote down vote up
private JSONObject sendRequest(String addUrl, String query, String action) throws IOException, JSONException {
    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("SOAPAction", action);
    connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException logOrIgnore) {
                log.error("Error while closing the connection");
            }
        }
    }
    InputStream response = connection.getInputStream();
    String out = "[Fault] No Response.";
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }
        out = sb.toString();
    }

    if (!out.isEmpty()) {
        return new JSONObject(out);
    } else {
        return null;
    }
}
 
Example 9
Source Project: micro-integrator   File: FileServiceApp.java    License: Apache License 2.0 5 votes vote down vote up
private void doPost(String url, String content) throws IOException {
    URL urlObj = new URL(url);
    URLConnection conn = urlObj.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.writeBytes(content);
    out.flush();
    out.close();
    conn.getInputStream().close();
}
 
Example 10
private String sendRequest(String addUrl, String request) throws IOException {
    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "application/json" + ";charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(request.getBytes(charset));
    } finally {
        if (output != null) {
            output.close();
        }
    }
    InputStream response = connection.getInputStream();
    String out = "[Fault] No Response.";
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }
        out = sb.toString();
    }
    return out;
}
 
Example 11
Source Project: elexis-3-core   File: JCifsTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void createWriteReadDeleteNonExistingFile() throws IOException{
	assumeTrue(servicesAreReachable);
	String nowString = LocalDateTime.now().toString();
	URL url = new URL(prefixUrl + "test.txt");
	if (url.getUserInfo() == null) {
		// not authenticated
		thrown.expect(SmbAuthException.class);
	}
	URLConnection openConnection = url.openConnection();
	try (SmbFile smbFile = (SmbFile) openConnection) {
		assertFalse(smbFile.exists());
		OutputStream os = openConnection.getOutputStream();
		IOUtils.write(nowString, os, Charset.defaultCharset());
		os.close();
		
		assertTrue(smbFile.exists());
		
		InputStream is = openConnection.getInputStream();
		String string = IOUtils.toString(is, "UTF-8");
		is.close();
		assertEquals(nowString, string);
		
		smbFile.delete();
		assertFalse(smbFile.exists());
	}
}
 
Example 12
Source Project: product-ei   File: Sample18TestCase.java    License: Apache License 2.0 5 votes vote down vote up
private void sendRequest(String addUrl, String query)
        throws IOException {
    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type",
            "application/xml;charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException logOrIgnore) {
                log.error("Error while closing the connection");
            }
        }
    }
    InputStream response = connection.getInputStream();
    String out = "[Fault] No Response.";
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }
        out = sb.toString();
    }
    response.close();
}
 
Example 13
private JSONArray getBusData(String bn, int dir) throws Exception{
	try {
		URL url = new URL(routedb + "?");
	    URLConnection conn = url.openConnection();
	    conn.setDoOutput(true);

	    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

	    writer.write("bn=" + bn + "&dir=" + dir);
	    writer.flush();
	    
	    String line;
	    String data = "";
	    
	    BufferedReader reader = new BufferedReader(new 
                InputStreamReader(conn.getInputStream()));
	    while ((line = reader.readLine()) != null) {
	        data += line;
	     }
	    
	    if (data == ""){
	    	return null;
	    }
	    
	    data = data.substring(2, data.length());
	    data = data.substring(0, data.length() - 2);
	    data = "[" + data + "]";
	    
	    if (data.equals("[]")){
	    	return null;
	    }
	    
		return new JSONArray(data);
	} catch (Exception e){
		return null;
	}
}
 
Example 14
Source Project: servicemix   File: Client.java    License: Apache License 2.0 5 votes vote down vote up
public void sendRequest() throws Exception {
       URLConnection connection = new URL("http://localhost:8181/cxf/HelloWorld")
               .openConnection();
       connection.setDoInput(true);
       connection.setDoOutput(true);
       OutputStream os = connection.getOutputStream();
       // Post the request file.
       InputStream fis = getClass().getClassLoader().getResourceAsStream("org/apache/servicemix/samples/cxf_osgi/request.xml");
       IOUtils.copy(fis, os);
       // Read the response.
       InputStream is = connection.getInputStream();
System.out.println("the response is ====> ");
System.out.println(IOUtils.toString(is));        

   }
 
Example 15
Source Project: samples   File: upload-app-s3.java    License: MIT License 4 votes vote down vote up
public static void uploadFileToS3(String filePath, String presignedUrl) {
    try {
        URLConnection urlconnection = null;
        File appFile = new File(filePath);
        URL url = new URL(presignedUrl);

        urlconnection = url.openConnection();
        urlconnection.setUseCaches(false);
        urlconnection.setDoOutput(true);
        urlconnection.setDoInput(true);

        if (urlconnection instanceof HttpURLConnection) {
            ((HttpURLConnection) urlconnection).setRequestMethod("PUT");
            ((HttpURLConnection) urlconnection).setRequestProperty("Content-Type", "application/octet-stream");
            ((HttpURLConnection) urlconnection).setRequestProperty("x-amz-tagging", "unsaved=true");
            ((HttpURLConnection) urlconnection).setRequestProperty("Content-Length", getFileSizeBytes(appFile));
            ((HttpURLConnection) urlconnection).connect();
        }

        BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
        FileInputStream bis = new FileInputStream(appFile);
        System.out.println("Total file size to read (in bytes) : " + bis.available());
        int i;
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.close();
        bis.close();

        InputStream inputStream;
        int responseCode = ((HttpURLConnection) urlconnection).getResponseCode();
        if ((responseCode >= 200) && (responseCode <= 202)) {
            inputStream = ((HttpURLConnection) urlconnection).getInputStream();
            int j;
            while ((j = inputStream.read()) > 0) {
                System.out.println(j);
            }

        } else {
            inputStream = ((HttpURLConnection) urlconnection).getErrorStream();
        }
        ((HttpURLConnection) urlconnection).disconnect();
        System.out.println("uploadFileToS3: " + ((HttpURLConnection) urlconnection).getResponseMessage());

    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}
 
Example 16
Source Project: SENS   File: SensUtils.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * 百度主动推送
 *
 * @param blogUrl 博客地址
 * @param token   百度推送token
 * @param urls    文章路径
 * @return String
 */
public static String baiduPost(String blogUrl, String token, String urls) {
    String url = "http://data.zz.baidu.com/urls?site=" + blogUrl + "&token=" + token;
    String result = "";
    PrintWriter out = null;
    BufferedReader in = null;
    try {
        //建立URL之间的连接
        URLConnection conn = new URL(url).openConnection();
        //设置通用的请求属性
        conn.setRequestProperty("Host", "data.zz.baidu.com");
        conn.setRequestProperty("User-Agent", "curl/7.12.1");
        conn.setRequestProperty("Content-Length", "83");
        conn.setRequestProperty("Content-Type", "text/plain");

        //发送POST请求必须设置如下两行
        conn.setDoInput(true);
        conn.setDoOutput(true);

        //获取conn对应的输出流
        out = new PrintWriter(conn.getOutputStream());
        out.print(urls.trim());
        //进行输出流的缓冲
        out.flush();
        //通过BufferedReader输入流来读取Url的响应
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != out) {
                out.close();
            }
            if (null != in) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}
 
Example 17
Source Project: XRTB   File: HttpPostGet.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Send an HTTP Post
 * @param targetURL
 *    String. The URL to transmit to.
 * @param data
 *            byte[]. The payload bytes.
 * @param connTimeout
 * 			  int. The connection timeout in ms
 * @param readTimeout
 * 			  int. The read timeout in ms.
 * @return byte[]. The contents of the POST return.
 * @throws Exception
 *             on network errors.
 */
public byte [] sendPost(String targetURL,  byte [] data, int connTimeout, int readTimeout) throws Exception {
	URLConnection connection = new URL(targetURL).openConnection();
	connection.setRequestProperty("Content-Type", "application/json");
	connection.setDoInput(true);
	connection.setDoOutput(true);
	connection.setConnectTimeout(connTimeout);
	connection.setReadTimeout(readTimeout);
	OutputStream output = connection.getOutputStream();
	
	try {
		output.write(data);
	} finally {
		try {
			output.close();
		} catch (IOException logOrIgnore) {
			logOrIgnore.printStackTrace();
		}
	}
	InputStream response = connection.getInputStream();
	
	http = (HttpURLConnection) connection;
	code = http.getResponseCode();
	
	String value = http.getHeaderField("Content-Encoding");
	
	if (value != null && value.equals("gzip")) {
		byte bytes [] = new byte[4096];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		GZIPInputStream gis = new GZIPInputStream(http.getInputStream());
		while(true) {
			int n = gis.read(bytes);
			if (n < 0) break;
			baos.write(bytes,0,n);
		}
		return baos.toByteArray();
	}
	
		

	byte [] b = getContents(response);
	if (b.length == 0)
		return null;
	return b;
}
 
Example 18
public TGShareSongResponse getResponse() throws Throwable {
	URL url = new URL(TGCommunityWeb.getHomeUrl(this.context) + "/rd.php/sharing/tuxguitar/upload.do");
	URLConnection conn = url.openConnection();
	conn.setDoInput(true);
	conn.setDoOutput(true);
	conn.setUseCaches(false);
	conn.setRequestProperty("Connection", "Keep-Alive");
	conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDARY);
	
	DataOutputStream out = new DataOutputStream( conn.getOutputStream() );
	
	// auth
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
	out.writeBytes("Content-Disposition: form-data; name=\"auth\";" + EOL);
	out.writeBytes(EOL);
	out.writeBytes(this.auth.getAuthCode());
	out.writeBytes(EOL);
	
	// title
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
	out.writeBytes("Content-Disposition: form-data; name=\"title\";" + EOL);
	out.writeBytes(EOL);
	out.writeBytes(this.file.getTitle());
	out.writeBytes(EOL);
	
	// description
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
	out.writeBytes("Content-Disposition: form-data; name=\"description\";" + EOL);
	out.writeBytes(EOL);
	out.writeBytes(this.file.getDescription());
	out.writeBytes(EOL);
	
	// tagkeys
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
	out.writeBytes("Content-Disposition: form-data; name=\"tagkeys\";" + EOL);
	out.writeBytes(EOL);
	out.writeBytes(this.file.getTagkeys());
	out.writeBytes(EOL);
	
	// file
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
	out.writeBytes("Content-Disposition: form-data; name=\"fileName\";" + " filename=\"" + this.file.getFilename() +"\"" + EOL);
	out.writeBytes(EOL);
	out.write( this.file.getFile() );
	out.writeBytes(EOL);
	
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + BOUNDARY_SEPARATOR + EOL);
	out.flush();
	out.close();
	
	return new TGShareSongResponse( conn.getInputStream() );
}
 
Example 19
/** do a POST to a URL and return the response stream for further processing elsewhere.
 *
 *
 * @param url
 * @return
 * @throws IOException
 */
public static InputStream doPOST(URL url, String data)

		throws IOException
{

	// Send data

	URLConnection conn = url.openConnection();

	conn.setDoOutput(true);

	try(OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) {

		wr.write(data);
		wr.flush();
	}


	// Get the response
	return conn.getInputStream();

}
 
Example 20
private static String doUrl(URL url, String authUser, String authPassword, String data, String ctype, String method) throws IOException {
    StringBuilder sb = new StringBuilder(5000);
    try {
        if(url != null) {
            String userPassword = authUser + ":" + authPassword;
            String encodedUserPassword = Base64.encodeBytes(userPassword.getBytes());
            URLConnection con = (HttpURLConnection) url.openConnection();
            Wandora.initUrlConnection(con);
            con.setRequestProperty ("Authorization", "Basic " + encodedUserPassword);

            con.setDoInput(true);
            con.setUseCaches(false);

            if(method != null && con instanceof HttpURLConnection) {
                ((HttpURLConnection) con).setRequestMethod(method);
                //System.out.println("****** Setting HTTP request method to "+method);
            }

            if(ctype != null) {
                con.setRequestProperty("Content-type", ctype);
            }

            if(data != null && data.length() > 0) {
                con.setRequestProperty("Content-length", data.length() + "");
                con.setDoOutput(true);
                PrintWriter out = new PrintWriter(con.getOutputStream());
                out.print(data);
                out.flush();
                out.close();
            }
            //DataInputStream in = new DataInputStream(con.getInputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));

            String s;
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
            in.close();
        }
    }
    catch(IOException ioe) {
        Wandora.getWandora().handleError(ioe);
    }
    catch(Exception e) {
        Wandora.getWandora().handleError(e);
    }
    return sb.toString();
}