java.net.URLConnection#getOutputStream ( )源码实例Demo

下面列出了java.net.URLConnection#getOutputStream ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: AthenaServing   文件: SslTest.java
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());
}
 
源代码2 项目: appengine-tck   文件: URLFetchTest.java
@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();
    }
}
 
源代码3 项目: quarkus   文件: ValidatorTestCase.java
@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"));
}
 
源代码4 项目: google-cloud-eclipse   文件: PackageImportTest.java
@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"));
  }
}
 
源代码5 项目: opencps-v2   文件: ZaloMapUtils.java
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);
		}
	}
 
源代码6 项目: RestServices   文件: Misc.java
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;
  }
 
源代码7 项目: phoebus   文件: XmlRpc.java
/** 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;
}
 
源代码8 项目: micro-integrator   文件: JSONClient.java
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;
    }
}
 
源代码9 项目: micro-integrator   文件: FileServiceApp.java
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();
}
 
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;
}
 
源代码11 项目: elexis-3-core   文件: JCifsTest.java
@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());
	}
}
 
源代码12 项目: product-ei   文件: Sample18TestCase.java
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();
}
 
源代码13 项目: KmbETA-API   文件: BusDatabase.java
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;
	}
}
 
源代码14 项目: servicemix   文件: Client.java
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));        

   }
 
源代码15 项目: samples   文件: upload-app-s3.java
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());
    }
}
 
源代码16 项目: SENS   文件: SensUtils.java
/**
 * 百度主动推送
 *
 * @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;
}
 
源代码17 项目: XRTB   文件: HttpPostGet.java
/**
 * 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;
}
 
源代码18 项目: tuxguitar   文件: TGShareSongRequest.java
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() );
}
 
源代码19 项目: biojava   文件: PdbIdLists.java
/** 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();

}
 
源代码20 项目: wandora   文件: WatsonTranslateBox.java
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();
}