java.net.HttpURLConnection#setDoOutput ( )源码实例Demo

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

源代码1 项目: apm-agent-java   文件: AbstractIntakeApiHandler.java
protected HttpURLConnection startRequest(String endpoint) throws IOException {
    final HttpURLConnection connection = apmServerClient.startRequest(endpoint);
    if (logger.isDebugEnabled()) {
        logger.debug("Starting new request to {}", connection.getURL());
    }
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setChunkedStreamingMode(DslJsonSerializer.BUFFER_SIZE);
    connection.setRequestProperty("Content-Encoding", "deflate");
    connection.setRequestProperty("Content-Type", "application/x-ndjson");
    connection.setUseCaches(false);
    connection.connect();
    os = new DeflaterOutputStream(connection.getOutputStream(), deflater);
    os.write(metaData);
    return connection;
}
 
public static void setHttpHeader(String cookie) {

        try {
            uc = (HttpURLConnection) u.openConnection();
            uc.setDoOutput(true);
            uc.setRequestProperty("Host", "www.enterupload.com");
            uc.setRequestProperty("Connection", "keep-alive");
            uc.setRequestProperty("Referer", "http://www.enterupload.com/");
            uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1");
            uc.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            uc.setRequestProperty("Accept-Encoding", "html");
            uc.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
            uc.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//            uc.setRequestProperty("Cookie", "");
            uc.setRequestMethod("POST");
            uc.setInstanceFollowRedirects(false);


        } catch (Exception e) {
            System.out.println("ex" + e.toString());
        }
    }
 
private int emitMetricsJson(HttpURLConnection connection, int timeout, String jsonData) throws IOException {
  connection.setRequestMethod("POST");
  connection.setRequestProperty("Content-Type", "application/json");
  connection.setRequestProperty("Connection", "Keep-Alive");
  connection.setConnectTimeout(timeout);
  connection.setReadTimeout(timeout);
  connection.setDoOutput(true);

  if (jsonData != null) {
    try (OutputStream os = connection.getOutputStream()) {
      os.write(jsonData.getBytes("UTF-8"));
    }
  }

  int statusCode = connection.getResponseCode();
  if (LOG.isDebugEnabled()) {
    LOG.debug("emitMetricsJson: statusCode = " + statusCode);
  }
  return statusCode;
}
 
源代码4 项目: appinventor-extensions   文件: Web.java
private static void writeRequestData(HttpURLConnection connection, byte[] postData)
    throws IOException {
  // According to the documentation at
  // http://developer.android.com/reference/java/net/HttpURLConnection.html
  // HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has
  // been called.
  connection.setDoOutput(true); // This makes it something other than a HTTP GET.
  // Write the data.
  connection.setFixedLengthStreamingMode(postData.length);
  BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
  try {
    out.write(postData, 0, postData.length);
    out.flush();
  } finally {
    out.close();
  }
}
 
源代码5 项目: SaveVolley   文件: HurlStack.java
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        /*
         * 使用 URL 连接进行输出,则将 DoOutput 标志设置为 true
         * 之后就可以使用conn.getOutputStream().write()
         */
        connection.setDoOutput(true);
        // 添加头信息 Content-Type
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        // DataOutputStream 写入 请求数据 byte[]
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}
 
private Pair<String, Integer> post(String url, String json, String token) throws IOException {
  URL createUrl = new URL(url);
  HttpURLConnection con = (HttpURLConnection) createUrl.openConnection();
  con.setRequestMethod("POST");
  con.setRequestProperty(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
  if (token != null)
    con.setRequestProperty("Authorization", "Bearer " + token);

  con.setDoOutput(true);
  OutputStream os = con.getOutputStream();
  os.write(json.getBytes(StandardCharsets.UTF_8));
  os.flush();
  os.close();

  con.connect();
  BufferedReader br2 = new BufferedReader(new InputStreamReader((InputStream) con.getContent(), StandardCharsets.UTF_8));
  String result = br2.lines().collect(Collectors.joining("\n"));
  int code = con.getResponseCode();
  con.disconnect();
  return new Pair<>(result, code);
}
 
源代码7 项目: recaptcha-codelab   文件: FeedbackServlet.java
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);
}
 
源代码8 项目: karate   文件: Consumer.java
public Payment create(Payment payment) {
    try {
        HttpURLConnection con = getConnection("/payments");
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json");
        String json = JsonUtils.toJson(payment);
        IOUtils.write(json, con.getOutputStream(), "utf-8");
        int status = con.getResponseCode();
        if (status != 200) {
            throw new RuntimeException("status code was " + status);
        }
        String content = IOUtils.toString(con.getInputStream(), "utf-8");
        return JsonUtils.fromJson(content, Payment.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
源代码9 项目: mblog   文件: HttpKit.java
private static HttpURLConnection initHttp(String url, String method, Map<String, String> headers)
        throws IOException {
    URL _url = new URL(url);
    HttpURLConnection http = (HttpURLConnection) _url.openConnection();

    http.setConnectTimeout(25000);

    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

    if ((headers != null) && (!headers.isEmpty())) {
        for (Entry entry : headers.entrySet()) {
            http.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
        }
    }
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}
 
源代码10 项目: android_maplib   文件: NetworkUtil.java
public static HttpResponse put(
        String targetURL,
        String payload,
        String username,
        String password,
        boolean readErrorResponseBody)
        throws IOException
{
    final HttpURLConnection conn = getHttpConnection(HTTP_PUT, targetURL, username, password);
    if (null == conn) {
        if (Constants.DEBUG_MODE)
            Log.d(TAG, "Error get connection object: " + targetURL);
        return new HttpResponse(ERROR_CONNECT_FAILED);
    }
    conn.setRequestProperty("Content-type", "application/json");
    // Allow Outputs
    conn.setDoOutput(true);

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

    writer.flush();
    writer.close();
    os.close();

    return getHttpResponse(conn, readErrorResponseBody);
}
 
源代码11 项目: xipki   文件: RestCaClient.java
private boolean simpleHttpGet(String url) throws IOException {
  HttpURLConnection conn = SdkUtil.openHttpConn(new URL(url));
  conn.setDoOutput(true);
  conn.setUseCaches(false);

  conn.setRequestMethod("GET");
  conn.setRequestProperty("Authorization", "Basic " + authorization);

  int responseCode = conn.getResponseCode();
  boolean ok = (responseCode == HttpURLConnection.HTTP_OK);
  if (!ok) {
    LOG.warn("bad response: {}    {}", conn.getResponseCode(), conn.getResponseMessage());
  }
  return ok;
}
 
源代码12 项目: gameserver   文件: Apple.java
/**
 * Receive iOS client's receipt data got from Apple Server
 * and verify it before adding money to users.
 *  
 * @param receiptData
 * @return
 */
public static String verifyIAP(String receiptData) {
	if ( StringUtil.checkNotEmpty(receiptData) ) {
		String json = MessageFormatter.format(IAP_JSON, receiptData).getMessage();
		logger.info("IAP json: {}", json);
		if ( iapVerifyURL != null ) {
			try {
				HttpURLConnection conn = (HttpURLConnection)iapVerifyURL.openConnection();
				conn.setRequestMethod("POST");
				conn.setDoInput(true);
				conn.setDoOutput(true);
				OutputStream os = conn.getOutputStream();
				os.write(json.getBytes());
				os.flush();
				int code = conn.getResponseCode();
				if ( code == 200 ) {
					BufferedInputStream is = new BufferedInputStream(conn.getInputStream());
					ByteArrayOutputStream baos = new ByteArrayOutputStream(30);
					int b = is.read();
					while ( b >= 0 ) {
						baos.write(b);
						b = is.read();
					}
					String response = new String(baos.toByteArray());
					return response;
				} else {
					logger.debug("Failed to verify iap receipt data. Http code: {}", code);
				}
			} catch (Exception e) {
				logger.debug("Failed to verify iap receipt data because of {}", e.toString());
			}
		}
	} else {
		logger.debug("#verifyIAP: receipt data is empty");
	}
	return null;
}
 
源代码13 项目: dubbo-postman   文件: Maven.java
void doDownLoadFile(String baseUrl,String filePath,String fileName) throws IOException{

    URL httpUrl=new URL(baseUrl);

    HttpURLConnection conn=(HttpURLConnection) httpUrl.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.connect();

    InputStream inputStream = conn.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(inputStream);

    //判断文件的保存路径后面是否以/结尾
    if (!filePath.endsWith("/")) {
    
        filePath += "/";
    
    }

    FileOutputStream fileOut = new FileOutputStream(filePath+fileName);
    BufferedOutputStream bos = new BufferedOutputStream(fileOut);

    byte[] buf = new byte[4096];
    int length = bis.read(buf);
    //保存文件
    while(length != -1)
    {
        bos.write(buf, 0, length);
        length = bis.read(buf);
    }
    
    bos.close();
    bis.close();
    conn.disconnect();
}
 
源代码14 项目: olingo-odata4   文件: BasicBatchITCase.java
private HttpURLConnection getConnection(final String content) throws MalformedURLException, IOException,
    ProtocolException {
  final URL url = getUrl();
  final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.POST.toString());
  connection.setRequestProperty(HttpHeader.CONTENT_TYPE, CONTENT_TYPE_HEADER_VALUE);
  connection.setRequestProperty(HttpHeader.ACCEPT, ACCEPT_HEADER_VALUE);
  connection.setDoOutput(true);
  final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
  writer.append(content);
  writer.close();
  connection.connect();
  return connection;
}
 
源代码15 项目: jboot   文件: GatewayHttpProxy.java
public void doSendRequest(String url, HttpServletRequest req, HttpServletResponse resp) throws Exception {

        HttpURLConnection conn = null;
        try {
            conn = getConnection(url);

            /**
             * 配置 HttpURLConnection 的 http 请求头
             */
            configConnection(conn, req);


            // get 请求
            if ("get".equalsIgnoreCase(req.getMethod())) {
                conn.connect();
            }
            // post 请求
            else {
                conn.setDoOutput(true);
                conn.setDoInput(true);
                copyRequestStreamToConnection(req, conn);
            }


            /**
             * 配置 HttpServletResponse 的 http 响应头
             */
            configResponse(resp, conn);

            /**
             * 复制链接的 inputStream 流到 Response
             */
            copyConnStreamToResponse(conn, resp);

        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
 
源代码16 项目: Abelana-Android   文件: Request.java
final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection)
throws IOException, JSONException {
    Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");

    int numRequests = requests.size();

    HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
    connection.setRequestMethod(connectionHttpMethod.name());

    URL url = connection.getURL();
    logger.append("Request:\n");
    logger.appendKeyValue("Id", requests.getId());
    logger.appendKeyValue("URL", url);
    logger.appendKeyValue("Method", connection.getRequestMethod());
    logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
    logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));

    connection.setConnectTimeout(requests.getTimeout());
    connection.setReadTimeout(requests.getTimeout());

    // If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will
    // turn it into a POST.
    boolean isPost = (connectionHttpMethod == HttpMethod.POST);
    if (!isPost) {
        logger.log();
        return;
    }

    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        if (hasOnProgressCallbacks(requests)) {
            ProgressNoopOutputStream countingStream = null;
            countingStream = new ProgressNoopOutputStream(requests.getCallbackHandler());
            processRequest(requests, null, numRequests, url, countingStream);

            int max = countingStream.getMaxProgress();
            Map<Request, RequestProgress> progressMap = countingStream.getProgressMap();

            BufferedOutputStream buffered = new BufferedOutputStream(connection.getOutputStream());
            outputStream = new ProgressOutputStream(buffered, requests, progressMap, max);
        }
        else {
            outputStream = new BufferedOutputStream(connection.getOutputStream());
        }

        processRequest(requests, logger, numRequests, url, outputStream);
    }
    finally {
        outputStream.close();
    }

    logger.log();
}
 
源代码17 项目: jus   文件: HurlStack.java
@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection,
        Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty(HEADER_CONTENT_TYPE,
                        request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        case Method.GET:
            // Not necessary to set the request method because connection defaults to GET but
            // being explicit here.
            connection.setRequestMethod("GET");
            break;
        case Method.DELETE:
            connection.setRequestMethod("DELETE");
            break;
        case Method.POST:
            connection.setRequestMethod("POST");
            addBodyIfExists(connection, request);
            break;
        case Method.PUT:
            connection.setRequestMethod("PUT");
            addBodyIfExists(connection, request);
            break;
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        case Method.PATCH:
            connection.setRequestMethod("PATCH");
            addBodyIfExists(connection, request);
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
源代码18 项目: xmu-2016-MrCode   文件: OrderAction.java
public Mrcodeorder createOrder(){
	//生成码团订单
	//收集数据
	try {
		Customer customer = (Customer)session.get(Const.CUSTOMER);
		String roomIds = getParameter("room");
		String contactorIds = getParameter("contactor");
		Date begin = (Date)session.get("begin");
		Date end = (Date)session.get("end");
		List<Grouppurchasevoucher> vouchers = (List<Grouppurchasevoucher>)session.get("vouchers");
		Float depositPrice = (float) 0;
		for(Grouppurchasevoucher g : vouchers){
			depositPrice += g.getPrice();
		}
		//生成订单
		Mrcodeorder mrcodeorder = new Mrcodeorder(customer, 
				MakeOrderNum.makeOrderNum(Thread.currentThread().getName()), 
				depositPrice, new Timestamp(System.currentTimeMillis()), 
				new HashSet<Grouppurchasevoucher>(vouchers));
		mrcodeorder = mrcodeorderService.getById(mrcodeorderService.save(mrcodeorder));
		//顾客类型 1出差  2游玩
		String ids = passwordService.getLatestCity(customer, pageBean);
		customer.setCusType(Predict.trafficOrVisit(ids));
		//消费水平 1高 2低
		int shopLevel = passwordService.getShopLevel(customer, pageBean) > 300 ? 1 : 2 ;
		customer.setShopLevel(shopLevel );
		customerService.update(customer);
		
		//把团购券设为已使用
		for(Grouppurchasevoucher voucher : vouchers){
			voucher.setUsed(1);
		}
		grouppurchasevoucherService.saveOrUpdateAll(vouchers);
		//生成各房间的密码钥匙
		List<Password> passwords = null;
		if ((passwords=passwordService.createPasswords(mrcodeorder, roomIds, contactorIds, begin, end))!=null) {
			//请求酒店可用的房间
			String url_str = "http://localhost:8080/JavaPrj_9/reserv.htm?action=createReservBymrcode";//获取用户认证的帐号URL
	        URL url = new URL(url_str);
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			// connection.connect();
			// 默认是get 方式
			connection.setRequestMethod("POST");
			// 设置是否向connection输出,如果是post请求,参数要放在http正文内,因此需要设为true
			connection.setDoOutput(true);
			// Post 请求不能使用缓存
			connection.setUseCaches(false);
			//要上传的参数  
			JsonConfig config = new JsonConfig();
			config.setExcludes(new String[] { "roomtype", "floor","roomdates","mrcodeorder","customer"});
			config.registerJsonValueProcessor(Timestamp.class, new JsonValueFormat());
			JSONArray jsonArray = JSONArray.fromObject(passwords,config);
			JSONObject json = new JSONObject();
			json.put("deposit", 0);
			json.put("orderCode", mrcodeorder.getOrderCode());
			json.put("passwords", jsonArray);
	        PrintWriter pw=new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"utf-8"));
	        String content = "json=" + json;  
	        pw.print(content);
	        pw.flush();
	        pw.close();
	        int code = connection.getResponseCode();
	        if (code == 404) {
	            throw new Exception("连接无效,找不到此次连接的会话信息!");
	        }
	        if (code == 500) {
	            throw new Exception("连接服务器发生内部错误!");
	        }
	        if (code != 200) {
	            throw new Exception("发生其它错误,连接服务器返回 " + code);
	        }
	        InputStream is = connection.getInputStream();
	        byte[] response = new byte[is.available()];
	        is.read(response);
	        is.close();
	        if (response == null || response.length == 0) {
	            throw new Exception("连接无效,找不到此次连接的会话信息!");
	        }
	        mrcodeorder.setPasswords(new HashSet<Password>(passwords));
			return mrcodeorder;
		}else {
			return null;
		}
	} catch (Exception e) {
		// TODO: handle exception
		return null;
	}
	
}
 
源代码19 项目: ZTuoExchange_framework   文件: GeetestLib.java
/**
 * 发送POST请求,获取服务器返回结果
 * 
 * @param getURL
 * @return 服务器返回结果
 * @throws IOException
 */
private String readContentFromPost(String URL, String data) throws IOException {
	
	gtlog(data);
	URL postUrl = new URL(URL);
	HttpURLConnection connection = (HttpURLConnection) postUrl
			.openConnection();

	connection.setConnectTimeout(2000);// 设置连接主机超时(单位:毫秒)
	connection.setReadTimeout(2000);// 设置从主机读取数据超时(单位:毫秒)
	connection.setRequestMethod("POST");
	connection.setDoInput(true);
	connection.setDoOutput(true);
	connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	
	// 建立与服务器的连接,并未发送数据
	connection.connect();
	
	 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), "utf-8");  
	 outputStreamWriter.write(data);  
	 outputStreamWriter.flush();
	 outputStreamWriter.close();
	
	if (connection.getResponseCode() == 200) {
		// 发送数据到服务器并使用Reader读取返回的数据
		StringBuffer sBuffer = new StringBuffer();

		InputStream inStream = null;
		byte[] buf = new byte[1024];
		inStream = connection.getInputStream();
		for (int n; (n = inStream.read(buf)) != -1;) {
			sBuffer.append(new String(buf, 0, n, "UTF-8"));
		}
		inStream.close();
		connection.disconnect();// 断开连接
           
		return sBuffer.toString();	
	}
	else {
		
		return "fail";
	}
}
 
源代码20 项目: azure-storage-android   文件: QueueRequest.java
/**
 * Sets the ACL for the queue. Sign with length of aclBytes.
 * 
 * @param uri
 *            The absolute URI to the queue.
 * @param queueOptions
 *            A {@link QueueRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation. Specify <code>null</code> to use the request options specified on the
 *            {@link CloudQueueClient}.
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * @return a HttpURLConnection configured for the operation.
 * @throws StorageException
 * */
public static HttpURLConnection setAcl(final URI uri, final QueueRequestOptions queueOptions,
        final OperationContext opContext) throws IOException, URISyntaxException, StorageException {
    final UriQueryBuilder builder = new UriQueryBuilder();
    builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.ACL);

    final HttpURLConnection request = BaseRequest.createURLConnection(uri, queueOptions, builder, opContext);

    request.setDoOutput(true);
    request.setRequestMethod(Constants.HTTP_PUT);

    return request;
}