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


Java HttpURLConnection.setDoOutput方法代碼示例

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


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

示例1: testRewind

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testRewind() throws Exception {
    // Post preserving redirect should fail.
    URL url = new URL(NativeTestServer.getRedirectToEchoBody());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length);
    try {
        OutputStream out = connection.getOutputStream();
        out.write(TestUtil.UPLOAD_DATA);
    } catch (HttpRetryException e) {
        assertEquals("Cannot retry streamed Http body", e.getMessage());
    }
    connection.disconnect();
}
 
開發者ID:lizhangqu,項目名稱:chromium-net-for-android,代碼行數:20,代碼來源:CronetFixedModeOutputStreamTest.java

示例2: getChallengeHeader

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * Get the digest challenge header by connecting to the resource
 * with no credentials.
 */
public static String getChallengeHeader(String url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.getOutputStream().close();
    try {
        conn.getInputStream().close();
    } catch (IOException ex) {
        if (401 == conn.getResponseCode()) {
            // we expect a 401-unauthorized response with the
            // WWW-Authenticate header to create the request with the
            // necessary auth data
            String hdr = conn.getHeaderField("WWW-Authenticate");
            if (hdr != null && !"".equals(hdr)) {
                return hdr;
            }
        } else if (400 == conn.getResponseCode()) {
            // 400 usually means that auth is disabled on the Fabric node
            throw new IOException("Fabric returns status 400. If authentication is disabled on the Fabric node, "
                    + "omit the `fabricUsername' and `fabricPassword' properties from your connection.");
        } else {
            throw ex;
        }
    }
    return null;
}
 
開發者ID:JuanJoseFJ,項目名稱:ProyectoPacientes,代碼行數:30,代碼來源:DigestAuthentication.java

示例3: connect

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Override
public void connect() throws IllegalStateException, IOException {
    if (isConnected()) {
        throw new IllegalStateException("Already connected");
    }

    String url = "http://" + hostname + ":" + port + "/metrics/job/" + URLEncoder.encode(job, "UTF-8");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("Content-Type", TextFormat.REQUEST_CONTENT_TYPE);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");

    conn.setConnectTimeout(10 * SECONDS_PER_MILLISECOND);
    conn.setReadTimeout(10 * SECONDS_PER_MILLISECOND);
    conn.connect();

    this.connection = conn;
    this.writer = new PrometheusTextWriter(new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8)));
    this.exporter = new DropwizardMetricsExporter(writer);
}
 
開發者ID:dhatim,項目名稱:dropwizard-prometheus,代碼行數:21,代碼來源:Pushgateway.java

示例4: postLogin

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * 登陸獲取 Cookie
 *
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private String postLogin(String username, String password) throws Exception {
    String meCookie = null;//(String) memcachedManager.get("PLX_" + username + "_" + password);
    if (meCookie != null && !meCookie.equals("")) {
        this.Cookie = meCookie;
        return meCookie;
    }
    URL url = new URL(PLX + "/WebRoot/LoginAction.do");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setUseCaches(false);

    con.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded; text/html; charset=UTF-8");
    con.setConnectTimeout(1000);
    con.setReadTimeout(3000);
    OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
    osw.write("activity=login&userId=" + username + "&password=" + password);
    osw.flush();
    osw.close();
    /////////////
    //從請求中獲取cookie列表
    String cookieskey = "Set-Cookie";
    Map<String, List<String>> maps = con.getHeaderFields();
    List<String> coolist = maps.get(cookieskey);
    Iterator<String> it = coolist.iterator();
    StringBuffer sbu = new StringBuffer();
    while (it.hasNext()) {
        sbu.append(it.next() + ";");
    }
    String cookies = sbu.toString();
    cookies = cookies.substring(0, cookies.length() - 1);
    this.Cookie = cookies;
    //memcachedManager.set("PLX_" + username + "_" + password, cookies, 300);
    return cookies;
}
 
開發者ID:NeilRen,項目名稱:NEILREN4J,代碼行數:46,代碼來源:PhilisenseKaoQinService.java

示例5: testGetOutputStreamAfterConnectionMade

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testGetOutputStreamAfterConnectionMade() throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setChunkedStreamingMode(0);
    assertEquals(200, connection.getResponseCode());
    try {
        connection.getOutputStream();
        fail();
    } catch (ProtocolException e) {
        // Expected.
    }
}
 
開發者ID:lizhangqu,項目名稱:chromium-net-for-android,代碼行數:18,代碼來源:CronetChunkedOutputStreamTest.java

示例6: sendParams

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * Send parameters to output stream of request
 *
 * @param request
 * @param params
 * @throws IOException
 */
protected void sendParams(HttpURLConnection request, Object params)
        throws IOException {
    request.setDoOutput(true);
    if (params != null) {
        request.setRequestProperty(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON
                + "; charset=" + CHARSET_UTF8); //$NON-NLS-1$
        byte[] data = toJson(params).getBytes(CHARSET_UTF8);
        request.setFixedLengthStreamingMode(data.length);
        BufferedOutputStream output = new BufferedOutputStream(
                request.getOutputStream(), bufferSize);
        try {
            output.write(data);
            output.flush();
        } finally {
            try {
                output.close();
            } catch (IOException ignored) {
                // Ignored
            }
        }
    } else {
        request.setFixedLengthStreamingMode(0);
        request.setRequestProperty("Content-Length", "0");
    }
}
 
開發者ID:tranleduy2000,項目名稱:javaide,代碼行數:33,代碼來源:GitHubClient.java

示例7: postAndParseJSON

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private JSONObject postAndParseJSON(URL url, String postData) throws IOException {
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  urlConnection.setDoOutput(true);
  urlConnection.setRequestMethod("POST");
  urlConnection.setRequestProperty(
          "Content-Type", "application/x-www-form-urlencoded");
  urlConnection.setRequestProperty(
          "charset", StandardCharsets.UTF_8.displayName());
  urlConnection.setRequestProperty(
          "Content-Length", Integer.toString(postData.length()));
  urlConnection.setUseCaches(false);
  urlConnection.getOutputStream()
          .write(postData.getBytes(StandardCharsets.UTF_8));
  JSONTokener jsonTokener = new JSONTokener(urlConnection.getInputStream());
  return new JSONObject(jsonTokener);
}
 
開發者ID:googlecodelabs,項目名稱:recaptcha-codelab,代碼行數:17,代碼來源:FeedbackServlet.java

示例8: post

import java.net.HttpURLConnection; //導入方法依賴的package包/類
protected JSONObject post(URL url, String json_body) throws IOException {

		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_body.getBytes("UTF-8"));
		os.close();

		// read the response
		InputStream in = new BufferedInputStream(conn.getInputStream());
		String result = IOUtils.toString(in, "UTF-8");
		JSONObject jsonObject = new JSONObject(result);

		in.close();
		conn.disconnect();

		return jsonObject;
	}
 
開發者ID:trvlrch,項目名稱:trvlr-backend,代碼行數:24,代碼來源:ApiService.java

示例9: doPostRequest

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private void doPostRequest(String destination, String parms) throws IOException {
    URL url = new URL(destination);
    String response = "";
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(parms);
    writer.flush();
    writer.close();
    os.close();

    conn.connect();
    int responseCode = conn.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        String line;
        BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line=br.readLine()) != null) {
            response+=line;
        }
    }
    else {
        response="";

    }
}
 
開發者ID:jsparber,項目名稱:CaptivePortalAutologin,代碼行數:34,代碼來源:CaptivePortalLoginActivity.java

示例10: prepareConnection

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Override
public void prepareConnection(HttpURLConnection urlConnection, HttpMethod httpMethod,
        String contentType) throws IOException {
    // Configure connection for request method
    urlConnection.setRequestMethod(httpMethod.getMethodName());
    urlConnection.setDoOutput(httpMethod.getDoOutput());
    urlConnection.setDoInput(httpMethod.getDoInput());
    if (contentType != null) {
        urlConnection.setRequestProperty("Content-Type", contentType);
    }
    // Set additional properties
    urlConnection.setRequestProperty("Accept-Charset", UTF8);
}
 
開發者ID:dreaminglion,項目名稱:iosched-reader,代碼行數:14,代碼來源:BasicRequestHandler.java

示例11: testPutFile

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Test
public void testPutFile() throws IOException {
    if (!judgeUserInfoValid()) {
        return;
    }
    String key = "ut/generate_url_test_upload.txt";
    File localFile = buildTestFile(1024);
    Date expirationTime = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
    URL url = cosclient.generatePresignedUrl(bucket, key, expirationTime, HttpMethodName.PUT);

    System.out.println(url.toString());

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("PUT");

    BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(localFile));
    int readByte = -1;
    while ((readByte = bis.read()) != -1) {
        bos.write(readByte);
    }
    bis.close();
    bos.close();
    int responseCode = connection.getResponseCode();
    assertEquals(200, responseCode);

    headSimpleObject(key, localFile.length(), Md5Utils.md5Hex(localFile));
    clearObject(key);
    localFile.delete();
}
 
開發者ID:tencentyun,項目名稱:cos-java-sdk-v5,代碼行數:32,代碼來源:GeneratePresignedUrlTest.java

示例12: addBodyIfExists

import java.net.HttpURLConnection; //導入方法依賴的package包/類
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();
    }
}
 
開發者ID:pooyafaroka,項目名稱:PlusGram,代碼行數:12,代碼來源:HurlStack.java

示例13: addRequestBodyIfNecessary

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private void addRequestBodyIfNecessary(String requestMethod, HttpURLConnection connection)
    throws IOException {
  if (requestMethod.equals("POST") || requestMethod.equals("PUT")) {
    connection.setDoOutput(true);
    OutputStream requestBody = connection.getOutputStream();
    requestBody.write('x');
    requestBody.close();
  }
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:10,代碼來源:ResponseCacheTest.java

示例14: addRequestBodyIfNecessary

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private void addRequestBodyIfNecessary(String requestMethod, HttpURLConnection invalidate)
    throws IOException {
  if (requestMethod.equals("POST") || requestMethod.equals("PUT")) {
    invalidate.setDoOutput(true);
    OutputStream requestBody = invalidate.getOutputStream();
    requestBody.write('x');
    requestBody.close();
  }
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:10,代碼來源:UrlConnectionCacheTest.java

示例15: main

import java.net.HttpURLConnection; //導入方法依賴的package包/類
public static void main ( String[] args ) {

        if ( args.length < 3 ) {
            System.err.println(JSF.class.getName() + " <view_url> <payload_type> <payload_arg>");
            System.exit(-1);
        }

        final Object payloadObject = Utils.makePayloadObject(args[ 1 ], args[ 2 ]);

        try {
            URL u = new URL(args[ 0 ]);

            URLConnection c = u.openConnection();
            if ( ! ( c instanceof HttpURLConnection ) ) {
                throw new IllegalArgumentException("Not a HTTP url");
            }

            HttpURLConnection hc = (HttpURLConnection) c;
            hc.setDoOutput(true);
            hc.setRequestMethod("POST");
            hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStream os = hc.getOutputStream();

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(payloadObject);
            oos.close();
            byte[] data = bos.toByteArray();
            String requestBody = "javax.faces.ViewState=" + URLEncoder.encode(Base64.encodeBase64String(data), "US-ASCII");
            os.write(requestBody.getBytes("US-ASCII"));
            os.close();

            System.err.println("Have response code " + hc.getResponseCode() + " " + hc.getResponseMessage());
        }
        catch ( Exception e ) {
            e.printStackTrace(System.err);
        }
        Utils.releasePayload(args[1], payloadObject);

    }
 
開發者ID:hucheat,項目名稱:APacheSynapseSimplePOC,代碼行數:41,代碼來源:JSF.java


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