本文整理汇总了Java中java.net.URLConnection.getOutputStream方法的典型用法代码示例。如果您正苦于以下问题:Java URLConnection.getOutputStream方法的具体用法?Java URLConnection.getOutputStream怎么用?Java URLConnection.getOutputStream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.URLConnection
的用法示例。
在下文中一共展示了URLConnection.getOutputStream方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: send
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Sends the request and returns the response.
*
* @return String
*/
public String send() throws Exception {
URLConnection con = this.url.openConnection();
con.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(this.body);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String response = "";
String buffer;
while ((buffer = in.readLine()) != null) {
response += buffer;
}
in.close();
return response;
}
示例2: shareAndGetResponse
import java.net.URLConnection; //导入方法依赖的package包/类
private String shareAndGetResponse(String selection, int languageDropdownId) throws IOException {
URL url = new URL("http://pastie.org/pastes");
URLConnection conn = url.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
String data = "paste[parser_id]=" + languageDropdownId +
"&paste[authorization]=burger&paste[restricted]=1&paste[body]=" + URLEncoder.encode(selection, "UTF-8");
writer.write(data);
writer.flush();
writer.close();
StringBuffer answer = loadResponse(conn);
return answer.toString();
}
示例3: post
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Performs an HTTP POST request.
* @param url The request URL.
* @param query The request payload, in string form.
* @param auth The content of the Authorization header.
* @return The response of the request in string form.
*/
public static String post(String url, String query, String auth) {
try {
URLConnection conn = open(url, auth);
OutputStream output = conn.getOutputStream();
output.write(query.getBytes(charset));
output.close();
InputStream response = conn.getInputStream();
String outputStr = null;
if (charset != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset));
for (String line; (line = reader.readLine()) != null;) {
outputStr = line;
}
reader.close();
}
return outputStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
示例4: post
import java.net.URLConnection; //导入方法依赖的package包/类
public static String post(URLConnection connection,
String stringWriter,
Credentials credentials) throws Exception {
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Authorization",
"Basic "
+ Base64.encode((credentials.getUserName() + ":" + new String(
credentials.getPassword())).getBytes()));
OutputStreamWriter postData = new OutputStreamWriter(connection.getOutputStream());
postData.write(stringWriter);
postData.flush();
postData.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = "";
String line = "";
while ((line = in.readLine()) != null)
response = response + line;
in.close();
return response;
}
示例5: postString
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Posts string data (i.e. JSON string) to the specified URL
* connection.
*
* @param con The URL connection. Must be in HTTP POST mode. Must not
* be {@code null}.
* @param data The string data to post. Must not be {@code null}.
*
* @throws JSONRPC2SessionException If an I/O exception is encountered.
*/
private static void postString(final URLConnection con, final String data)
throws JSONRPC2SessionException {
try {
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
wr.write(data);
wr.flush();
wr.close();
} catch (IOException e) {
throw new JSONRPC2SessionException(
"Network exception: " + e.getMessage(),
JSONRPC2SessionException.NETWORK_EXCEPTION,
e);
}
}
示例6: postYbApi
import java.net.URLConnection; //导入方法依赖的package包/类
public String postYbApi(String apiName,String query) throws IOException {
String url = "https://openapi.yiban.cn/" + apiName;
String charset = "UTF-8";
URLConnection connection = new URL(url).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
connection.setDoOutput(true);
connection.setDoInput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.print(query);
out.flush();
InputStream response = connection.getInputStream();
StringBuilder sb=new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(response));
String read;
while((read=br.readLine()) != null) {
sb.append(read);
}
br.close();
return sb.toString();
}
示例7: privateApiQuery
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Performs a raw private API query.
* @param method the REST resource
* @param postParam the JSON to send in the request body.
* @return result JSON
*/
//Thanks to sampey from https://www.cryptopia.co.nz/Forum/Thread/262
private String privateApiQuery(String method, String postParam) {
if (secretKey == null) {
throw new CryptopiaClientException("Please set your secret key before attempting " +
"to access any private API methods.");
}
if (key == null) {
throw new CryptopiaClientException("Please set your key before attempting " +
"to access any private API methods.");
}
BufferedReader in = null;
try {
final String urlMethod = String.format("%s/%s/%s", ROOT_URL, PRIVATE_PATH, method);
final String nonce = String.valueOf(System.currentTimeMillis());
final StringBuilder reqSignature = new StringBuilder();
reqSignature
.append(key)
.append("POST")
.append(URLEncoder.encode(urlMethod, StandardCharsets.UTF_8.toString()).toLowerCase())
.append(nonce)
.append(getMD5_B64(postParam));
final StringBuilder auth = new StringBuilder();
auth.append("amx ")
.append(key)
.append(":")
.append(sha256_B64(reqSignature.toString()))
.append(":")
.append(nonce);
final URLConnection con = new URL(urlMethod).openConnection();
con.setDoOutput(true);
final HttpsURLConnection httpsConn = (HttpsURLConnection) con;
httpsConn.setRequestMethod("POST");
httpsConn.setInstanceFollowRedirects(true);
con.setRequestProperty("Authorization", auth.toString());
con.setRequestProperty("Content-Type", "application/json");
final DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParam);
wr.flush();
wr.close();
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
return response.toString();
}catch (Exception e) {
throw new CryptopiaClientException("An error occurred communicating with Cryptopia.", e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignored) {}
}
}
}
示例8: sendButtonActionPerformed
import java.net.URLConnection; //导入方法依赖的package包/类
private void sendButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_sendButtonActionPerformed
{//GEN-HEADEREND:event_sendButtonActionPerformed
try
{
// Construct data
String data = URLEncoder.encode("messages", "UTF-8") + "=" + URLEncoder.encode(logTextarea.getText(), "UTF-8");
// Send data
URL url = new URL("http://unimozer.fisch.lu/boot.php?who=moenagade");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line... --> do nothing
}
wr.close();
rd.close();
}
catch (Exception ex)
{
// ignore
}
this.dispose();
}
示例9: completeRequest
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Performs any additional processing necessary to complete the request.
**/
protected void completeRequest( URLConnection connection ) throws IOException {
super.completeRequest( connection );
connection.setDoInput( true );
connection.setDoOutput( true );
OutputStream stream = connection.getOutputStream();
writeMessageBody( stream );
stream.flush();
stream.close();
}
示例10: post
import java.net.URLConnection; //导入方法依赖的package包/类
public static final byte[] post(String url, String data, Map<String, String> headers) {
try {
URLConnection conn = new URL(url).openConnection();
conn.setDoOutput(true);
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
OutputStream os = conn.getOutputStream();
OutputStreamWriter wr = new OutputStreamWriter(os);
wr.write(data);
wr.flush();
wr.close();
os.close();
System.out.println("HTTP Response headers: " + conn.getHeaderFields());
List<String> header = conn.getHeaderFields().get("Content-Disposition");
if (header != null && header.size() > 0) {
headers.put("Content-Disposition", header.get(0));
}
header = conn.getHeaderFields().get("Content-Type");
if (header != null && header.size() > 0) {
headers.put("Content-Type", header.get(0));
}
InputStream is = conn.getInputStream();
byte[] result = IOUtils.toByteArray(is);
is.close();
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
示例11: doPlipPost
import java.net.URLConnection; //导入方法依赖的package包/类
private String doPlipPost() throws IOException {
String boundary = Long.toHexString(System.currentTimeMillis());
String crlf = "\r\n";
String login = Base64.getEncoder().encodeToString(PLIP_REST_PROVIDER_CREDENTIALS.getBytes());
URLConnection connection = new URL(plipUrl).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setRequestProperty("Authorization", "Basic " + login);
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, CHARSET), true);
writer.append("--").append(boundary).append(crlf);
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"").append(pdbFilePath.getFileName().toString()).append("\"").append(crlf);
writer.append("Content-Type: text/plain; charset=" + CHARSET).append(crlf); // Text file itself must be saved in this charset!
writer.append(crlf).flush();
Files.copy(pdbFilePath, output);
output.flush();
writer.append(crlf).flush();
writer.append("--").append(boundary).append("--").append(crlf).flush();
int responseCode = ((HttpURLConnection) connection).getResponseCode();
logger.info("PLIP REST service response code is " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String outputContent;
StringBuilder response = new StringBuilder();
while ((outputContent = in.readLine()) != null) {
response.append(outputContent);
}
in.close();
return response.toString();
}
示例12: completeRequest
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Performs any additional processing necessary to complete the request.
**/
protected void completeRequest( URLConnection connection ) throws IOException {
((HttpURLConnection) connection).setRequestMethod( getMethod() );
connection.setDoInput( true );
connection.setDoOutput( true );
OutputStream stream = connection.getOutputStream();
writeMessageBody( stream );
stream.flush();
stream.close();
}
示例13: createOutputStream
import java.net.URLConnection; //导入方法依赖的package包/类
public static OutputStream createOutputStream(String uri) throws IOException {
// URI was specified. Handle relative URIs.
final String expanded = XMLEntityManager.expandSystemId(uri, null, true);
final URL url = new URL(expanded != null ? expanded : uri);
OutputStream out = null;
String protocol = url.getProtocol();
String host = url.getHost();
// Use FileOutputStream if this URI is for a local file.
if (protocol.equals("file")
&& (host == null || host.length() == 0 || host.equals("localhost"))) {
File file = new File(getPathWithoutEscapes(url.getPath()));
if (!file.exists()) {
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
}
out = new FileOutputStream(file);
}
// Try to write to some other kind of URI. Some protocols
// won't support this, though HTTP should work.
else {
URLConnection urlCon = url.openConnection();
urlCon.setDoInput(false);
urlCon.setDoOutput(true);
urlCon.setUseCaches(false); // Enable tunneling.
if (urlCon instanceof HttpURLConnection) {
// The DOM L3 REC says if we are writing to an HTTP URI
// it is to be done with an HTTP PUT.
HttpURLConnection httpCon = (HttpURLConnection) urlCon;
httpCon.setRequestMethod("PUT");
}
out = urlCon.getOutputStream();
}
return out;
}
示例14: post
import java.net.URLConnection; //导入方法依赖的package包/类
public String post(String url, String params) {
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
// conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;
// MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
try (PrintWriter out = new PrintWriter(conn.getOutputStream())) {
// 发送请求参数
out.print(params);
// flush输出流的缓冲
out.flush();
}
// 定义BufferedReader输入流来读取URL的响应
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = in.readLine()) != null) {
result += line;
}
}
} catch (Exception e) {
throw new ZhhrUtilException("发送POST请求出现异常!原因:" + e.getMessage());
}
return result;
}
示例15: invoke
import java.net.URLConnection; //导入方法依赖的package包/类
public PropBagEx invoke(BlackBoardSessionData data, String servlet, String name, Collection<NameValue> parameters)
throws IOException
{
long startTime = System.currentTimeMillis();
BlindSSLSocketFactory.register();
// Setup URLConnection to appropriate servlet/jsp
URLConnection con = new URL(this.url, servlet).openConnection();
con.setConnectTimeout(TIMEOUT);
con.setReadTimeout(TIMEOUT);
con.setDoInput(true);
con.setDoOutput(true);
String token = data.getBlackBoardSession();
// BB7 contains '@@'
final int expectedTokenLength = PASS_LENGTH + (token.startsWith("@@") ? 2 : 0);
if( token.length() == expectedTokenLength )
{
con.setRequestProperty("Cookie", "session_id=" /* @@" */+ token + ";");
}
// Open output stream and send username and password
PrintWriter conout = new PrintWriter(con.getOutputStream());
StringBuilder out = new StringBuilder();
out.append("method=" + name + "&");
if( parameters != null )
{
for( NameValue pair : parameters )
{
out.append(pair.getValue() + "=" + encode(pair.getName()) + "&");
}
}
conout.print(out.toString());
conout.close();
InputStream in = con.getInputStream();
PropBagEx xml = parseInputStream(in);
String cookie = con.getHeaderField("Set-Cookie");
if( cookie == null )
{
Map<String, List<String>> headerFields = con.getHeaderFields();
if( headerFields != null && !Check.isEmpty(headerFields.get("Set-Cookie")) )
{
cookie = headerFields.get("Set-Cookie").get(0);
}
}
xml.setNode("cookie", cookie);
in.close();
int buildingBlockDuration = xml.getIntNode("@invocationDuration", -1);
int thisMethodDuration = (int) ((System.currentTimeMillis() - startTime) / 1000);
StringBuilder sb = new StringBuilder("URL request from EQUELLA to Blackboard took ");
sb.append(thisMethodDuration);
sb.append(" second(s), where ");
sb.append(buildingBlockDuration);
sb.append(" second(s) where spent in the Building Block");
LOGGER.info(sb.toString());
return xml;
}