當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpURLConnection.getOutputStream方法代碼示例

本文整理匯總了Java中java.net.HttpURLConnection.getOutputStream方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpURLConnection.getOutputStream方法的具體用法?Java HttpURLConnection.getOutputStream怎麽用?Java HttpURLConnection.getOutputStream使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.net.HttpURLConnection的用法示例。


在下文中一共展示了HttpURLConnection.getOutputStream方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: request

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private StringBuffer request(String urlString, JSONObject jsonObj) {
    // TODO Auto-generated method stub

    StringBuffer chaine = new StringBuffer("");
    try {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", "");
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.connect();

        Log.d("REQUESTOUTPUT", "requesting");
        byte[] b = jsonObj.toString().getBytes();
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(b);


        InputStream inputStream = connection.getInputStream();

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        while ((line = rd.readLine()) != null) {
            chaine.append(line);
        }

    } catch (IOException e) {
        // writing exception to log
        e.printStackTrace();
    }

    return chaine;
}
 
開發者ID:xeliot,項目名稱:ChewSnap,代碼行數:34,代碼來源:SignupActivity.java

示例2: sendBytes

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * Send bytes
 * 
 * @param con
 * @param msg
 * @throws IOException
 */
private static void sendBytes(HttpURLConnection con, String message)
		throws IOException {
	OutputStream os = null;
	try {
		os = con.getOutputStream();
		if (null == message) {
			os.write(0);
		} else {
			os.write(message.getBytes(defaulEncoding));
		}
		os.flush();
	} finally {
		if (null != os)
			os.close();
	}
}
 
開發者ID:jiangzongyao,項目名稱:kettle_support_kettle8.0,代碼行數:24,代碼來源:HTTPD.java

示例3: transferUsageStats

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * 
 * @return true on success
 */
public boolean transferUsageStats(ProgressListener progressListener) throws Exception {
	progressListener.setCompleted(10);
	String xml = XMLTools.toString(getXML());
	progressListener.setCompleted(20);
	URL url = new URL(WEB_SERVICE_URL);
	HttpURLConnection con = (HttpURLConnection) url.openConnection();
	con.setDoOutput(true);
	con.setRequestMethod("POST");
	WebServiceTools.setURLConnectionDefaults(con);
	try (Writer writer = new OutputStreamWriter(con.getOutputStream())) {
		progressListener.setCompleted(30);
		writer.write(xml);
		writer.flush();
		progressListener.setCompleted(90);
		if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
			throw new IOException("Responde from server: " + con.getResponseMessage());
		} else {
			return true;
		}
	} finally {
		progressListener.complete();
	}
}
 
開發者ID:transwarpio,項目名稱:rapidminer,代碼行數:28,代碼來源:UsageStatistics.java

示例4: testFixedLengthStreamingModeWriteOneByte

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testFixedLengthStreamingModeWriteOneByte()
        throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length);
    OutputStream out = connection.getOutputStream();
    for (int i = 0; i < TestUtil.UPLOAD_DATA.length; i++) {
        // Write one byte at a time.
        out.write(TestUtil.UPLOAD_DATA[i]);
    }
    assertEquals(200, connection.getResponseCode());
    assertEquals("OK", connection.getResponseMessage());
    assertEquals(TestUtil.UPLOAD_DATA_STRING, TestUtil.getResponseAsString(connection));
    connection.disconnect();
}
 
開發者ID:lizhangqu,項目名稱:chromium-net-for-android,代碼行數:22,代碼來源:CronetFixedModeOutputStreamTest.java

示例5: streamedBodyIsNotRetried

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Test public void streamedBodyIsNotRetried() throws Exception {
  server.enqueue(new MockResponse()
      .setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST));

  urlFactory = new OkUrlFactory(defaultClient().newBuilder()
      .dns(new DoubleInetAddressDns())
      .build());
  HttpURLConnection connection = urlFactory.open(server.url("/").url());
  connection.setDoOutput(true);
  connection.setChunkedStreamingMode(100);
  OutputStream os = connection.getOutputStream();
  os.write("OutputStream is no fun.".getBytes("UTF-8"));
  os.close();

  try {
    connection.getResponseCode();
    fail();
  } catch (IOException expected) {
  }

  assertEquals(1, server.getRequestCount());
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:23,代碼來源:URLConnectionTest.java

示例6: configConnection

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Override
protected void configConnection(final HttpURLConnection httpURLConnection, final HTTPRequest request)
		throws IOException {
	httpURLConnection.setDoOutput(true);
	httpURLConnection.setUseCaches(false);

	if (null != request.getPayload()) {
		final OutputStream outputStream = httpURLConnection.getOutputStream();

		outputStream.write(request.getPayload());

		outputStream.flush();
		outputStream.close();
	}

	// TODO: request.getPayloadMap()
}
 
開發者ID:daima,項目名稱:solo-spring,代碼行數:18,代碼來源:UrlFetchPutHandler.java

示例7: testPostWithContentLengthOneMassiveWrite

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testPostWithContentLengthOneMassiveWrite() throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    byte[] largeData = TestUtil.getLargeData();
    connection.setRequestProperty("Content-Length",
            Integer.toString(largeData.length));
    OutputStream out = connection.getOutputStream();
    out.write(largeData);
    assertEquals(200, connection.getResponseCode());
    assertEquals("OK", connection.getResponseMessage());
    TestUtil.checkLargeData(TestUtil.getResponseAsString(connection));
    connection.disconnect();
}
 
開發者ID:lizhangqu,項目名稱:chromium-net-for-android,代碼行數:20,代碼來源:CronetBufferedOutputStreamTest.java

示例8: testWriteLessThanContentLength

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testWriteLessThanContentLength()
        throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    // Set a content length that's 1 byte more.
    connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length + 1);
    OutputStream out = connection.getOutputStream();
    out.write(TestUtil.UPLOAD_DATA);
    try {
        connection.getResponseCode();
        fail();
    } catch (ProtocolException e) {
        // Expected.
    }
    connection.disconnect();
}
 
開發者ID:lizhangqu,項目名稱:chromium-net-for-android,代碼行數:23,代碼來源:CronetFixedModeOutputStreamTest.java

示例9: getResponse

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Override
FSDataOutputStream getResponse(final HttpURLConnection conn)
    throws IOException {
  return new FSDataOutputStream(new BufferedOutputStream(
      conn.getOutputStream(), bufferSize), statistics) {
    @Override
    public void close() throws IOException {
      try {
        super.close();
      } finally {
        try {
          validateResponse(op, conn, true);
        } finally {
          conn.disconnect();
        }
      }
    }
  };
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:20,代碼來源:WebHdfsFileSystem.java

示例10: doUpload

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Exception {
  int n = 512 * 1024;
  server.setBodyLimit(0);
  server.enqueue(new MockResponse());

  HttpURLConnection conn = urlFactory.open(server.url("/").url());
  conn.setDoOutput(true);
  conn.setRequestMethod("POST");
  if (uploadKind == TransferKind.CHUNKED) {
    conn.setChunkedStreamingMode(-1);
  } else {
    conn.setFixedLengthStreamingMode(n);
  }
  OutputStream out = conn.getOutputStream();
  if (writeKind == WriteKind.BYTE_BY_BYTE) {
    for (int i = 0; i < n; ++i) {
      out.write('x');
    }
  } else {
    byte[] buf = new byte[writeKind == WriteKind.SMALL_BUFFERS ? 256 : 64 * 1024];
    Arrays.fill(buf, (byte) 'x');
    for (int i = 0; i < n; i += buf.length) {
      out.write(buf, 0, Math.min(buf.length, n - i));
    }
  }
  out.close();
  assertEquals(200, conn.getResponseCode());
  RecordedRequest request = server.takeRequest();
  assertEquals(n, request.getBodySize());
  if (uploadKind == TransferKind.CHUNKED) {
    assertTrue(request.getChunkSizes().size() > 0);
  } else {
    assertTrue(request.getChunkSizes().isEmpty());
  }
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:36,代碼來源:URLConnectionTest.java

示例11: writeRequestParas

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private static void writeRequestParas(HttpURLConnection connection, String query) throws IOException {
    byte[] buffer = query.getBytes(_charset);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(buffer, 0, buffer.length);
    outputStream.flush();
    outputStream.close();
}
 
開發者ID:MalongTech,項目名稱:productai-java-sdk,代碼行數:8,代碼來源:RequestHelper.java

示例12: httpPost

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * 指定ContentType調用接口
 *
 * @param url
 * @param body
 * @param ContentType
 * @return
 */
public static String httpPost(String url, String body, String ContentType) {
    String bs = null;
    try {
        URL uri = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setReadTimeout(CONNECTION_TIME_OUT_TIME);
        conn.setConnectTimeout(CONNECTION_TIME_OUT_TIME);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", ContentType);

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(body.toString().getBytes());

        outStream.flush();

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream in = conn.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[256];
            int n;
            while ((n = in.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            byte[] b = out.toByteArray();
            in.close();
            bs = new String(b);
        }
        outStream.close();
        conn.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bs;
}
 
開發者ID:quickhybrid,項目名稱:quickhybrid-android,代碼行數:46,代碼來源:HttpUtil.java

示例13: excuteCBASQuery

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private String excuteCBASQuery(String query) throws Exception {
    URL url = new URL(getCbasURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded");
    connection.setRequestProperty("ignore-401",
            "true");

    String encodedQuery = URLEncoder.encode(query, "UTF-8");
    String payload = "statement=" + encodedQuery;

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.writeBytes(payload);
    out.flush();
    out.close();

    int responseCode = connection.getResponseCode();

    BufferedReader in = new BufferedReader(
            new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    return response.toString();
}
 
開發者ID:couchbaselabs,項目名稱:GitTalent,代碼行數:34,代碼來源:AnalyticsController.java

示例14: doInBackground

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Override
protected final Void doInBackground(ItemState... itemStates) {
    for (ItemState state : itemStates) {
        try {
            HttpURLConnection urlConnection = ConnectionUtil.createUrlConnection(serverUrl + "/rest/items/" + state.mItemName + "/state");
            try {
                urlConnection.setRequestMethod("PUT");
                urlConnection.setDoOutput(true);
                urlConnection.setRequestProperty("Content-Type", "text/plain");
                urlConnection.setRequestProperty("Accept", "application/json");

                OutputStreamWriter osw = new OutputStreamWriter(urlConnection.getOutputStream());
                osw.write(state.mItemState);
                osw.flush();
                osw.close();
                Log.v("Habpanelview", "set request response: " + urlConnection.getResponseMessage()
                        + "(" + urlConnection.getResponseCode() + ")");
            } finally {
                urlConnection.disconnect();
            }
        } catch (IOException | GeneralSecurityException e) {
            Log.e("Habpanelview", "Failed to set state for item " + state.mItemName, e);
        }

        if (isCancelled()) {
            return null;
        }
    }
    return null;
}
 
開發者ID:vbier,項目名稱:habpanelviewer,代碼行數:31,代碼來源:SetItemStateTask.java

示例15: sendPost

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * POST請求
 * 
 * @param url 發送請求的 URL
 * @param param 請求應該與目標協議一致,name1=value1&name2=value2
 * @param auth basic認證信息 username:password
 * @param info k-v 加入瀏覽器需要的信息
 * @return 可能為空
 */
public static String sendPost(String url, String param, String auth, Map<String, String> info) throws Exception {
    // 1.打開連接
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    buliderConnectionHeader(conn);
    addAuthInfo(conn, null == auth ? EMPTY_ABYTE : auth.getBytes());
    addHttpInfo(conn, info);
    // 發送POST請求必須設置如下兩行
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.connect();

    // 2.設置請求參數
    PrintWriter out = new PrintWriter(conn.getOutputStream());
    out.print(param);
    out.flush();

    // 3.接受返回數據
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line, result = "";
    while ((line = in.readLine()) != null) {
        result += line;
    }
    out.close();
    in.close();
    conn.disconnect();
    return result;
}
 
開發者ID:jiumao-org,項目名稱:wechat-mall,代碼行數:38,代碼來源:HttpUtil.java


注:本文中的java.net.HttpURLConnection.getOutputStream方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。