本文整理了Java中java.net.HttpURLConnection.getOutputStream()
方法的一些代码示例,展示了HttpURLConnection.getOutputStream()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpURLConnection.getOutputStream()
方法的具体详情如下:
包路径:java.net.HttpURLConnection
类名称:HttpURLConnection
方法名:getOutputStream
暂无
canonical example by Tabnine
public void postRequest(String urlStr, String jsonBodyStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
try (OutputStream outputStream = httpURLConnection.getOutputStream()) {
outputStream.write(jsonBodyStr.getBytes());
outputStream.flush();
}
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
// ... do something with line
}
}
} else {
// ... do something with unsuccessful response
}
}
代码示例来源:origin: google/physical-web
/**
* Helper method to make an HTTP request.
* @param urlConnection The HTTP connection.
*/
public void writeToUrlConnection(HttpURLConnection urlConnection) throws IOException {
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
OutputStream os = urlConnection.getOutputStream();
os.write(mJsonObject.toString().getBytes("UTF-8"));
os.close();
}
代码示例来源:origin: mcxiaoke/android-volley
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
throws IOException, AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
connection.setDoOutput(true);
connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(body);
out.close();
}
}
}
代码示例来源:origin: ACRA/acra
@SuppressWarnings("WeakerAccess")
protected void writeContent(@NonNull HttpURLConnection connection, @NonNull Method method, @NonNull T content) throws IOException {
// write output - see http://developer.android.com/reference/java/net/HttpURLConnection.html
connection.setRequestMethod(method.name());
connection.setDoOutput(true);
// Disable ConnectionPooling because otherwise OkHttp ConnectionPool will try to start a Thread on #connect
System.setProperty("http.keepAlive", "false");
connection.connect();
final OutputStream outputStream = senderConfiguration.compress() ? new GZIPOutputStream(connection.getOutputStream(), ACRAConstants.DEFAULT_BUFFER_SIZE_IN_BYTES)
: new BufferedOutputStream(connection.getOutputStream());
try {
write(outputStream, content);
outputStream.flush();
} finally {
IOUtils.safeClose(outputStream);
}
}
代码示例来源:origin: wildfly/wildfly
try {
if (inputData != null) {
urlConnection.setDoOutput(true);
outputStream = urlConnection.getOutputStream();
outputStream.write(inputData);
inputStream = urlConnection.getInputStream();
payload = Util.readFileContents(urlConnection.getInputStream());
代码示例来源:origin: voldemort/voldemort
routingType,
"POST");
conn.setDoOutput(true);
if(vectorClock != null) {
conn.setRequestProperty(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, vectorClock);
conn.setRequestProperty("Content-Type", ContentType);
conn.setRequestProperty("Content-Length", contentLength);
OutputStream out = conn.getOutputStream();
out.write(value.getBytes());
out.close();
代码示例来源:origin: spotify/helios
private HttpURLConnection post(final String path, final byte[] body) throws IOException {
final URL url = new URL(masterEndpoint() + path);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.getOutputStream().write(body);
return connection;
}
}
代码示例来源:origin: chentao0707/SimplifyReader
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
throws IOException, AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
connection.setDoOutput(true);
connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(body);
out.close();
}
}
}
代码示例来源:origin: javamelody/javamelody
public void post(ByteArrayOutputStream payload) throws IOException {
final HttpURLConnection connection = (HttpURLConnection) openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
if (payload != null) {
final OutputStream outputStream = connection.getOutputStream();
payload.writeTo(outputStream);
outputStream.flush();
}
final int status = connection.getResponseCode();
if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
final String error = InputOutput.pumpToString(connection.getErrorStream(),
Charset.forName("UTF-8"));
final String msg = "Error connecting to " + url + '(' + status + "): " + error;
throw new IOException(msg);
}
connection.disconnect();
}
代码示例来源:origin: wildfly/wildfly
try {
if (inputData != null) {
urlConnection.setDoOutput(true);
outputStream = urlConnection.getOutputStream();
outputStream.write(inputData);
payload = getBytes(urlConnection.getInputStream());
代码示例来源:origin: googleapis/google-cloud-java
protected final String sendPostRequest(String request) throws IOException {
URL url = new URL("http", DEFAULT_HOST, this.port, request);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream out = con.getOutputStream();
out.write("".getBytes());
out.flush();
InputStream in = con.getInputStream();
String response = CharStreams.toString(new InputStreamReader(con.getInputStream()));
in.close();
return response;
}
代码示例来源:origin: jiangqqlmj/FastDev4Android
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
throws IOException, AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
connection.setDoOutput(true);
connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(body);
out.close();
}
}
}
代码示例来源:origin: google/agera
@NonNull
private HttpResponse getHttpResponseResult(final @NonNull HttpRequest request,
@NonNull final HttpURLConnection connection) throws IOException {
connection.setConnectTimeout(request.connectTimeoutMs);
connection.setReadTimeout(request.readTimeoutMs);
connection.setInstanceFollowRedirects(request.followRedirects);
connection.setUseCaches(request.useCaches);
connection.setDoInput(true);
connection.setRequestMethod(request.method);
for (final Entry<String, String> headerField : request.header.entrySet()) {
connection.addRequestProperty(headerField.getKey(), headerField.getValue());
}
final byte[] body = request.body;
if (body.length > 0) {
connection.setDoOutput(true);
final OutputStream out = connection.getOutputStream();
try {
out.write(body);
} finally {
out.close();
}
}
final String responseMessage = connection.getResponseMessage();
return httpResponse(connection.getResponseCode(),
responseMessage != null ? responseMessage : "",
getHeader(connection), getByteArray(connection));
}
代码示例来源:origin: languagetool-org/languagetool
@NotNull
private HttpURLConnection postToServer(String json, URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try {
try (DataOutputStream dos = new DataOutputStream(conn.getOutputStream())) {
//System.out.println("POSTING: " + json);
dos.write(json.getBytes("utf-8"));
}
} catch (IOException e) {
throw new RuntimeException("Could not connect OpenNMT server at " + url);
}
return conn;
}
代码示例来源:origin: wildfly/wildfly
public Response put(String preSignedUrl, S3Object object, Map headers) throws IOException {
HttpURLConnection request = makePreSignedRequest("PUT", preSignedUrl, headers);
request.setDoOutput(true);
request.getOutputStream().write(object.data == null? new byte[]{} : object.data);
return new Response(request);
}
代码示例来源:origin: testcontainers/testcontainers-java
public void callCouchbaseRestAPI(String url, String payload) throws IOException {
String fullUrl = urlBase + url;
@Cleanup("disconnect")
HttpURLConnection httpConnection = (HttpURLConnection) ((new URL(fullUrl).openConnection()));
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
String encoded = Base64.encode((clusterUsername + ":" + clusterPassword).getBytes("UTF-8"));
httpConnection.setRequestProperty("Authorization", "Basic " + encoded);
@Cleanup
DataOutputStream out = new DataOutputStream(httpConnection.getOutputStream());
out.writeBytes(payload);
out.flush();
httpConnection.getResponseCode();
}
代码示例来源:origin: spring-projects/spring-framework
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
addHeaders(this.connection, headers);
// JDK <1.8 doesn't support getOutputStream with HTTP DELETE
if (getMethod() == HttpMethod.DELETE && bufferedOutput.length == 0) {
this.connection.setDoOutput(false);
}
if (this.connection.getDoOutput() && this.outputStreaming) {
this.connection.setFixedLengthStreamingMode(bufferedOutput.length);
}
this.connection.connect();
if (this.connection.getDoOutput()) {
FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream());
}
else {
// Immediately trigger the request in a no-output scenario as well
this.connection.getResponseCode();
}
return new SimpleClientHttpResponse(this.connection);
}
代码示例来源:origin: sohutv/cachecloud
private static HttpURLConnection sendPost(String reqUrl,
Map<String, String> parameters, String encoding, int connectTimeout, int readTimeout) {
HttpURLConnection urlConn = null;
try {
String params = generatorParamString(parameters, encoding);
URL url = new URL(reqUrl);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
// urlConn
// .setRequestProperty(
// "User-Agent",
// "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3");
urlConn.setConnectTimeout(connectTimeout);// (单位:毫秒)jdk
urlConn.setReadTimeout(readTimeout);// (单位:毫秒)jdk 1.5换成这个,读操作超时
urlConn.setDoOutput(true);
// String按照字节处理是一个好方法
byte[] b = params.getBytes(encoding);
urlConn.getOutputStream().write(b, 0, b.length);
urlConn.getOutputStream().flush();
urlConn.getOutputStream().close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return urlConn;
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public ClientHttpResponse call() throws Exception {
SimpleBufferingClientHttpRequest.addHeaders(connection, headers);
// JDK <1.8 doesn't support getOutputStream with HTTP DELETE
if (getMethod() == HttpMethod.DELETE && bufferedOutput.length == 0) {
connection.setDoOutput(false);
}
if (connection.getDoOutput() && outputStreaming) {
connection.setFixedLengthStreamingMode(bufferedOutput.length);
}
connection.connect();
if (connection.getDoOutput()) {
FileCopyUtils.copy(bufferedOutput, connection.getOutputStream());
}
else {
// Immediately trigger the request in a no-output scenario as well
connection.getResponseCode();
}
return new SimpleClientHttpResponse(connection);
}
});
代码示例来源:origin: ethereum/ethereumj
private String postQuery(String endPoint, String json) throws IOException {
URL url = new URL(endPoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = null;
try (Scanner scanner = new Scanner(in, "UTF-8")) {
result = scanner.useDelimiter("\\A").next();
}
in.close();
conn.disconnect();
return result;
}
内容来源于网络,如有侵权,请联系作者删除!