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

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

源代码1 项目: netbeans   文件: RunnerRestCloudDeploy.java
/**
 * Handle sending data to server using HTTP command interface.
 * <p/>
 * This is based on reading the code of
 * <code>CLIRemoteCommand.java</code>
 * from the server's code repository. Since some asadmin commands
 * need to send multiple files, the server assumes the input is a ZIP
 * stream.
 */
@Override
protected void handleSend(HttpURLConnection hconn) throws IOException {
    //InputStream istream = getInputStream();
    if (command.path == null) {
        throw new GlassFishIdeException("The path attribute of deploy command"
                + " has to be non-empty!");
    }
    OutputStreamWriter wr = new OutputStreamWriter(hconn.getOutputStream());
    writeParam(wr, "file", command.path.getAbsolutePath());
    if (command.account != null) {
        writeParam(wr, "account", command.account);
    }
    writeBinaryFile(wr, hconn.getOutputStream(), command.path);
    wr.append("--" + multipartBoundary + "--").append(NEWLINE);
    wr.close();
}
 
源代码2 项目: contribution   文件: SourceforgeRssPublisher.java
/**
 * Publish release notes.
 *
 * @throws IOException if problem with access to files appears.
 */
public void publish() throws IOException {
    final int postsCountBefore = getPostsCount();

    final HttpURLConnection conn = (HttpURLConnection) new URL(POST_URL).openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    final OutputStream os = conn.getOutputStream();
    final String postText = new String(Files.readAllBytes(Paths.get(postFilename)),
            StandardCharsets.UTF_8);
    os.write(String.format(POST_TEMPLATE, bearerToken, releaseNumber, postText)
            .getBytes(StandardCharsets.UTF_8));
    os.flush();

    final int responseCode = conn.getResponseCode();
    conn.disconnect();

    // Sourceforge may not response correctly, so we also compare te number of posts in
    // RSS feed before and after publication in such cases to test whether it was successful
    if (responseCode != HttpURLConnection.HTTP_OK && getPostsCount() == postsCountBefore) {
        throw new IOException("Failed to post on RSS with HTTP error code : "
                + responseCode);
    }
}
 
源代码3 项目: ontology-java-sdk   文件: DeployDemo.java
public static Object send(String url, Object request) throws IOException {
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        try (OutputStreamWriter w = new OutputStreamWriter(connection.getOutputStream())) {
            w.write(JSON.toJSONString(request));
        }
        try (InputStreamReader r = new InputStreamReader(connection.getInputStream())) {
            StringBuffer temp = new StringBuffer();
            int c = 0;
            while ((c = r.read()) != -1) {
                temp.append((char) c);
            }
            //System.out.println("result:"+temp.toString());
            return JSON.parseObject(temp.toString(), Map.class);
        }
    } catch (IOException e) {
    }
    return null;
}
 
源代码4 项目: aliyun-tablestore-java-sdk   文件: HttpResponse.java
public static HttpResponse getResponse(HttpRequest request) throws IOException {
    OutputStream out = null;
    InputStream content = null;
    HttpResponse response = null;
    HttpURLConnection httpConn = request.getHttpConnection();

    try {
        httpConn.connect();
        if (null != request.getHttpContent() && request.getHttpContent().length > 0) {
            out = httpConn.getOutputStream();
            out.write(request.getHttpContent());
        }
        content = httpConn.getInputStream();
        response = new HttpResponse(httpConn.getURL().toString());
        pasrseHttpConn(response, httpConn, content);
        return response;
    } catch (IOException e) {
        content = httpConn.getErrorStream();
        response = new HttpResponse(httpConn.getURL().toString());
        pasrseHttpConn(response, httpConn, content);
        return response;
    } finally {
        if (content != null) { content.close(); }
        httpConn.disconnect();
    }
}
 
源代码5 项目: gameserver   文件: YeepayTest.java
@Test
public void testFunc() throws Exception {
	URL url = new URL("http://192.168.0.77/kupai");
	HttpURLConnection conn = (HttpURLConnection)url.openConnection();
	conn.setRequestMethod("POST");
	conn.setDoInput(true);
	conn.setDoOutput(true);
	OutputStream os = conn.getOutputStream();
	os.write(post.getBytes());
	os.close();
	Object obj = conn.getContent();
	int code = conn.getResponseCode();
	System.out.println("code:"+code+", obj:"+obj);
	fail("Not yet implemented");
}
 
源代码6 项目: volley_demo   文件: HurlStack.java
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();
    }
}
 
源代码7 项目: wildfly-core   文件: HttpRequest.java
/**
 * Executes an HTTP request to write the specified message.
 *
 * @param spec The {@link URL} in String form
 * @param message Message to write
 * @param timeout Timeout value
 * @param unit Timeout units
 * @param requestMethod Name of the HTTP method to execute (ie. HEAD, GET, POST)
 * @return
 * @throws MalformedURLException
 * @throws ExecutionException
 * @throws TimeoutException
 */
private static String execRequestMethod(final String spec, final String message, final long timeout, final TimeUnit unit, final String requestMethod) throws MalformedURLException, ExecutionException, TimeoutException {

    if(requestMethod==null||requestMethod.isEmpty()){
        throw new IllegalArgumentException("Request Method must be specified (ie. GET, PUT, DELETE etc)");
    }

    final URL url = new URL(spec);
    Callable<String> task = new Callable<String>() {
        @Override
        public String call() throws Exception {
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod(requestMethod);
            final OutputStream out = conn.getOutputStream();
            try {
                write(out, message);
                return processResponse(conn);
            }
            finally {
                out.close();
            }
        }
    };
    try {
        return execute(task, timeout, unit);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
源代码8 项目: Instagram-Profile-Downloader   文件: InstaUtils.java
public static String login(String username, String pass) throws Exception {
    getInitCookies(ig);

    URLConnection connection = new URL(igAuth).openConnection();
    if(connection instanceof HttpURLConnection){
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
        httpURLConnection.setRequestMethod(HttpPost.METHOD_NAME);
        httpURLConnection = addPostHeaders(httpURLConnection);

        String query = new Builder().appendQueryParameter("username", username).appendQueryParameter("password", pass).build().getEncodedQuery();
        OutputStream outputStream = httpURLConnection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, HTTP.UTF_8));
        bufferedWriter.write(query);
        bufferedWriter.flush();
        bufferedWriter.close();
        outputStream.close();
        httpURLConnection.connect();

        if(httpURLConnection.getResponseCode() != HttpStatus.SC_OK){
            return "bad_request";
        }

        extractAndSetCookies(httpURLConnection);
        JSONObject jsonObject = new JSONObject(buildResultString(httpURLConnection));
        if(jsonObject.get("user").toString().isEmpty()){
            return BuildConfig.VERSION_NAME;
        }

        return jsonObject.get("authenticated").toString();
    }

    throw new IOException("Url is not valid");
}
 
源代码9 项目: incubator-pinot   文件: AutoAddInvertedIndex.java
private boolean updateIndexConfig(String tableName, TableConfig tableConfig)
    throws Exception {
  String request =
      ControllerRequestURLBuilder.baseUrl("http://" + _controllerAddress).forTableUpdateIndexingConfigs(tableName);
  HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(request).openConnection();
  httpURLConnection.setDoOutput(true);
  httpURLConnection.setRequestMethod("PUT");

  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
  writer.write(tableConfig.toJsonString());
  writer.flush();

  BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
  return reader.readLine().equals("done");
}
 
源代码10 项目: ambari-metrics   文件: HttpSinkProvider.java
@Override
public void sinkMetricData(Collection<TimelineMetrics> metrics) {
  HttpURLConnection connection = null;
  try {
    connection = connectUrl.startsWith("https") ? getSSLConnection(connectUrl) : getConnection(connectUrl);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setConnectTimeout(getSinkTimeOutSeconds());
    connection.setReadTimeout(getSinkTimeOutSeconds());
    connection.setDoOutput(true);

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

    int statusCode = connection.getResponseCode();

    if (statusCode != 200) {
      LOG.info("Unable to POST metrics to external sink, " + connectUrl +
        ", statusCode = " + statusCode);
    } else {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Metrics posted to external sink " + connectUrl);
      }
    }
    cleanupInputStream(connection.getInputStream());

  } catch (IOException io) {
    LOG.warn("Unable to sink data to external system.", io);
  }
}
 
源代码11 项目: lastfm-java   文件: Caller.java
private HttpURLConnection openPostConnection(String method, Map<String, String> params) throws IOException {
	HttpURLConnection urlConnection = openConnection(apiRootUrl);
	urlConnection.setRequestMethod("POST");
	urlConnection.setDoOutput(true);
	OutputStream outputStream = urlConnection.getOutputStream();
	BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
	String post = buildPostBody(method, params);
	log.info("Post body: " + post);
	writer.write(post);
	writer.close();
	return urlConnection;
}
 
源代码12 项目: openjdk-jdk8u-backup   文件: StreamingRetry.java
void test(String method) throws Exception {
    ss = new ServerSocket(0);
    ss.setSoTimeout(ACCEPT_TIMEOUT);
    int port = ss.getLocalPort();

    Thread otherThread = new Thread(this);
    otherThread.start();

    try {
        URL url = new URL("http://localhost:" + port + "/");
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setDoOutput(true);
        if (method != null)
            uc.setRequestMethod(method);
        uc.setChunkedStreamingMode(4096);
        OutputStream os = uc.getOutputStream();
        os.write("Hello there".getBytes());

        InputStream is = uc.getInputStream();
        is.close();
    } catch (IOException expected) {
        //expected.printStackTrace();
    } finally {
        ss.close();
        otherThread.join();
    }
}
 
源代码13 项目: hadoop   文件: TransferFsImage.java
private static void writeFileToPutRequest(Configuration conf,
    HttpURLConnection connection, File imageFile, Canceler canceler)
    throws FileNotFoundException, IOException {
  connection.setRequestProperty(CONTENT_TYPE, "application/octet-stream");
  connection.setRequestProperty(CONTENT_TRANSFER_ENCODING, "binary");
  OutputStream output = connection.getOutputStream();
  FileInputStream input = new FileInputStream(imageFile);
  try {
    copyFileToStream(output, imageFile, input,
        ImageServlet.getThrottler(conf), canceler);
  } finally {
    IOUtils.closeStream(input);
    IOUtils.closeStream(output);
  }
}
 
源代码14 项目: netbeans   文件: RunnerRestDisable.java
@Override
protected void handleSend(HttpURLConnection hconn) throws IOException {
    CommandTargetName commandApp = (CommandTargetName)command;
    String target = commandApp.target;
    OutputStreamWriter wr =
            new OutputStreamWriter(hconn.getOutputStream());
    StringBuilder data = new StringBuilder();
    data.append("name=").append(commandApp.name);
    if (target != null) {
        data.append("&target=").append(commandApp.target);
    }

    wr.write(data.toString());
    wr.close();
}
 
源代码15 项目: jfinal-weixin   文件: MediaApi.java
/**
	 * 获取永久素材
	 * @param url 素材地址
	 * @return params post参数
	 * @return InputStream 流,考虑到这里可能返回json或file
	 * @throws IOException
	 */
	private static InputStream downloadMaterial(String url, String params) throws IOException {
		URL _url = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
		// 连接超时
		conn.setConnectTimeout(25000);
		// 读取超时 --服务器响应比较慢,增大时间
		conn.setReadTimeout(25000);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "Keep-Alive");
		conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.connect();
		if (StrKit.notBlank(params)) {
			OutputStream out = conn.getOutputStream();
			out.write(params.getBytes(DEFAULT_CHARSET));
			out.flush();
			IOUtils.closeQuietly(out);
		}
		InputStream input = conn.getInputStream();
//		// 关闭连接
//		if (conn != null) {
//			conn.disconnect();
//		}
		return input;
	}
 
源代码16 项目: che   文件: HttpRequestHelper.java
public static String requestString(
    int timeout, String url, String method, Object body, Pair<String, ?>... parameters)
    throws IOException, ServerException, ForbiddenException, NotFoundException,
        UnauthorizedException, ConflictException {
  final String authToken = EnvironmentContext.getCurrent().getSubject().getToken();
  if ((parameters != null && parameters.length > 0) || authToken != null) {
    final UriBuilder ub = UriBuilder.fromUri(url);
    // remove sensitive information from url.
    ub.replaceQueryParam("token", null);

    if (parameters != null && parameters.length > 0) {
      for (Pair<String, ?> parameter : parameters) {
        ub.queryParam(parameter.first, parameter.second);
      }
    }
    url = ub.build().toString();
  }
  final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
  conn.setConnectTimeout(timeout > 0 ? timeout : 60000);
  conn.setReadTimeout(timeout > 0 ? timeout : 60000);
  try {
    conn.setRequestMethod(method);
    // drop a hint for server side that we want to receive application/json
    //            conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    if (authToken != null) {
      conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authToken);
    }
    if (body != null) {
      //                conn.addRequestProperty(HttpHeaders.CONTENT_TYPE,
      // MediaType.APPLICATION_JSON);
      conn.setDoOutput(true);

      if (HttpMethod.DELETE.equals(method)) { // to avoid jdk bug described here
        // http://bugs.java.com/view_bug.do?bug_id=7157360
        conn.setRequestMethod(HttpMethod.POST);
        conn.setRequestProperty("X-HTTP-Method-Override", HttpMethod.DELETE);
      }

      try (OutputStream output = conn.getOutputStream()) {
        output.write(DtoFactory.getInstance().toJson(body).getBytes());
      }
    }

    final int responseCode = conn.getResponseCode();
    if ((responseCode / 100) != 2) {
      InputStream in = conn.getErrorStream();
      if (in == null) {
        in = conn.getInputStream();
      }
      final String str;
      try (Reader reader = new InputStreamReader(in)) {
        str = CharStreams.toString(reader);
      }
      final String contentType = conn.getContentType();
      if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON)) {
        final ServiceError serviceError =
            DtoFactory.getInstance().createDtoFromJson(str, ServiceError.class);
        if (serviceError.getMessage() != null) {
          if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) {
            throw new ForbiddenException(serviceError);
          } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) {
            throw new NotFoundException(serviceError);
          } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
            throw new UnauthorizedException(serviceError);
          } else if (responseCode == Response.Status.CONFLICT.getStatusCode()) {
            throw new ConflictException(serviceError);
          } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
            throw new ServerException(serviceError);
          }
          throw new ServerException(serviceError);
        }
      }
      // Can't parse content as json or content has format other we expect for error.
      throw new IOException(
          String.format(
              "Failed access: %s, method: %s, response code: %d, message: %s",
              UriBuilder.fromUri(url).replaceQuery("token").build(), method, responseCode, str));
    }

    //            final String contentType = conn.getContentType();

    //            if (!(contentType == null ||
    // contentType.startsWith(MediaType.APPLICATION_JSON))) {
    //                throw new IOException(conn.getResponseMessage());
    //            }

    try (Reader reader = new InputStreamReader(conn.getInputStream())) {
      return CharStreams.toString(reader);
    }
  } finally {
    conn.disconnect();
  }
}
 
源代码17 项目: x-pipe   文件: HickwallClient.java
private boolean send(String s) throws IOException {
    HttpURLConnection httpURLConnection = this.connection;
    if(httpURLConnection == null) {
        this.connection = httpURLConnection = getConnection();
    }
    boolean isValidConnection = false;

    boolean var5 = false;
    OutputStream out = null;
    label99:
    {
        try {
            isValidConnection = true;
            out = httpURLConnection.getOutputStream();
            out.write(s.getBytes(StandardCharsets.UTF_8));
            out.flush();
            int code = httpURLConnection.getResponseCode();
            if (code == 200) {
                var5 = true;
                isValidConnection = false;
                break label99;
            }

            logger.warn("error " + code);
            var5 = false;
            isValidConnection = false;
        } catch (IOException e) {
            try {
                this.connection.disconnect();
            } catch (Exception ex) {
                logger.debug("[send]", ex);
            }
        } finally {
            if (isValidConnection) {
                closeIfNotValidConnect(httpURLConnection);
            }
        }
    }

    closeIfNotValidConnect(httpURLConnection);

    return var5;
}
 
源代码18 项目: voip_android   文件: MainActivity.java
private String login(long uid) {
    //调用app自身的登陆接口获取im服务必须的access token
    String URL = "http://demo.gobelieve.io";
    String uri = String.format("%s/auth/token", URL);

    try {
        java.net.URL url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-type", "application/json");
        connection.connect();

        JSONObject json = new JSONObject();
        json.put("uid", uid);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
        writer.write(json.toString());
        writer.close();

        int responseCode = connection.getResponseCode();
        if(responseCode != HttpURLConnection.HTTP_OK) {
            System.out.println("login failure code is:" + responseCode);
            return null;
        }

        InputStream inputStream = connection.getInputStream();

        //inputstream -> string
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        String str = result.toString(StandardCharsets.UTF_8.name());


        JSONObject jsonObject = new JSONObject(str);
        String accessToken = jsonObject.getString("token");
        return accessToken;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}
 
源代码19 项目: samples   文件: upload-app-s3.java
public static String createAnAppOrVersion(String filename, String appPath) {
    try {
        JsonObject jsonObject = new JsonObject();
        if (filename != null && filename.length() > 0) {
            jsonObject.addProperty("filename", filename);
        }
        jsonObject.addProperty("appPath", appPath);

        URL uri = new URL("https://api.kobiton.com/v1/apps");
        HttpURLConnection con = (HttpURLConnection) uri.openConnection();

        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        String postData = jsonObject.toString();

        con.setRequestProperty("Authorization", generateBasicAuth());
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");

        OutputStream os = con.getOutputStream();
        os.write(postData.getBytes());
        os.flush();

        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        in.close();
        con.disconnect();

        System.out.println("createAnAppOrVersion: " + response.toString());
        return response.toString();
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }

    return "";
}
 
源代码20 项目: xipki   文件: CaMgmtClient.java
private byte[] transmit(MgmtAction action, MgmtRequest req, boolean voidReturn)
    throws CaMgmtException {
  initIfNotDone();

  byte[] reqBytes = req == null ? null : JSON.toJSONBytes(req);
  int size = reqBytes == null ? 0 : reqBytes.length;

  URL url = actionUrlMap.get(action);

  try {
    HttpURLConnection httpUrlConnection = IoUtil.openHttpConn(url);

    if (httpUrlConnection instanceof HttpsURLConnection) {
      if (sslSocketFactory != null) {
        ((HttpsURLConnection) httpUrlConnection).setSSLSocketFactory(sslSocketFactory);
      }
      if (hostnameVerifier != null) {
        ((HttpsURLConnection) httpUrlConnection).setHostnameVerifier(hostnameVerifier);
      }
    }

    httpUrlConnection.setDoOutput(true);
    httpUrlConnection.setUseCaches(false);

    httpUrlConnection.setRequestMethod("POST");
    httpUrlConnection.setRequestProperty("Content-Type", REQUEST_CT);
    httpUrlConnection.setRequestProperty("Content-Length", java.lang.Integer.toString(size));
    OutputStream outputstream = httpUrlConnection.getOutputStream();
    if (size != 0) {
      outputstream.write(reqBytes);
    }
    outputstream.flush();

    if (httpUrlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
      InputStream in = httpUrlConnection.getInputStream();

      boolean inClosed = false;
      try {
        String responseContentType = httpUrlConnection.getContentType();
        if (!RESPONSE_CT.equals(responseContentType)) {
          throw new CaMgmtException(
              "bad response: mime type " + responseContentType + " not supported!");
        }

        if (voidReturn) {
          return null;
        } else {
          inClosed = true;
          return IoUtil.read(httpUrlConnection.getInputStream());
        }
      } finally {
        if (in != null & !inClosed) {
          in.close();
        }
      }
    } else {
      String errorMessage = httpUrlConnection.getHeaderField(HttpConstants.HEADER_XIPKI_ERROR);
      if (errorMessage == null) {
        StringBuilder sb = new StringBuilder(100);
        sb.append("server returns ").append(httpUrlConnection.getResponseCode());
        String respMsg = httpUrlConnection.getResponseMessage();
        if (StringUtil.isNotBlank(respMsg)) {
          sb.append(" ").append(respMsg);
        }
        throw new CaMgmtException(sb.toString());
      } else {
        throw new CaMgmtException(errorMessage);
      }
    }
  } catch (IOException ex) {
    throw new CaMgmtException(
        "IOException while sending message to the server: " + ex.getMessage(), ex);
  }
}