java.net.HttpURLConnection.setRequestProperty()方法的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(12.4k)|赞(0)|评价(0)|浏览(560)

本文整理了Java中java.net.HttpURLConnection.setRequestProperty()方法的一些代码示例,展示了HttpURLConnection.setRequestProperty()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpURLConnection.setRequestProperty()方法的具体详情如下:
包路径:java.net.HttpURLConnection
类名称:HttpURLConnection
方法名:setRequestProperty

HttpURLConnection.setRequestProperty介绍

暂无

代码示例

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: jmxtrans/jmxtrans

public void configure(HttpURLConnection httpURLConnection) throws ProtocolException {
  httpURLConnection.setRequestMethod(requestMethod);
  httpURLConnection.setDoInput(true);
  httpURLConnection.setDoOutput(true);
  httpURLConnection.setReadTimeout(readTimeoutInMillis);
  if (contentType != null) httpURLConnection.setRequestProperty("Content-Type", contentType);
  if (authorization != null) httpURLConnection.setRequestProperty("Authorization", authorization);
  httpURLConnection.setRequestProperty("User-Agent", userAgent);
}

代码示例来源:origin: RipMeApp/ripme

/**
 * @param url
 *      Target URL
 * @return 
 *      Returns connection length
 */
private int getTotalBytes(URL url) throws IOException {
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setRequestMethod("HEAD");
  conn.setRequestProperty("accept",  "*/*");
  conn.setRequestProperty("Referer", this.url.toExternalForm()); // Sic
  conn.setRequestProperty("User-agent", AbstractRipper.USER_AGENT);
  return conn.getContentLength();
}

代码示例来源:origin: jenkinsci/jenkins

HttpURLConnection con = open(new URL(home));
  if (auth != null) con.setRequestProperty("Authorization", auth);
  con.connect();
  if(con.getResponseCode()!=200
  || con.getHeaderField("X-Hudson")==null) {
    System.err.println(home+" is not Hudson ("+con.getResponseMessage()+")");
URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/");
  HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult"));
  if (auth != null) con.setRequestProperty("Authorization", auth);
  con.connect();
  if(con.getResponseCode()!=200) {
    System.err.println(jobURL + " is not a valid external job (" + con.getResponseCode() + " " + con.getResponseMessage() + ")");
    return -1;
  HttpURLConnection con = open(new URL(home +
      "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'"));
  if (auth != null) con.setRequestProperty("Authorization", auth);
  String line = IOUtils.readFirstLine(con.getInputStream(),"UTF-8");
  String[] components = line.split(":");
  if (components.length == 2) {
      if (auth != null) con.setRequestProperty("Authorization", auth);
      if (crumbField != null && crumbValue != null) {
        con.setRequestProperty(crumbField, crumbValue);
      con.setDoOutput(true);

代码示例来源:origin: graphhopper/graphhopper

public HttpURLConnection createConnection(String urlStr) throws IOException {
  URL url = new URL(urlStr);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  // Will yield in a POST request: conn.setDoOutput(true);
  conn.setDoInput(true);
  conn.setUseCaches(true);
  conn.setRequestProperty("Referrer", referrer);
  conn.setRequestProperty("User-Agent", userAgent);
  // suggest respond to be gzipped or deflated (which is just another compression)
  // http://stackoverflow.com/q/3932117
  conn.setRequestProperty("Accept-Encoding", acceptEncoding);
  conn.setReadTimeout(timeout);
  conn.setConnectTimeout(timeout);
  return conn;
}

代码示例来源:origin: Atmosphere/atmosphere

public void request(String urlString) {
  HttpURLConnection urlConnection = null;
  try {
    URL url = new URL(urlString);
    urlConnection = openURLConnection(url);
    urlConnection.setInstanceFollowRedirects(true);
    urlConnection.setRequestMethod(GET_METHOD_NAME);
    urlConnection.setRequestProperty("User-agent", uaName + " (" + osString + ")");
    logger.debug("Sending Server's information to Atmosphere's Google Analytics {} {}", urlString, uaName + " (" + osString + ")");
    urlConnection.connect();
    int responseCode = getResponseCode(urlConnection);
    if (responseCode != HttpURLConnection.HTTP_OK) {
      logError("JGoogleAnalytics: Error tracking, url=" + urlString);
    } else {
      logMessage(SUCCESS_MESSAGE);
    }
  } catch (Exception e) {
    logError(e.getMessage());
  } finally {
    if (urlConnection != null) {
      urlConnection.disconnect();
    }
  }
}

代码示例来源:origin: czy1121/update

private HttpURLConnection create(URL url) throws IOException {
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestProperty("Accept", "application/*");
  connection.setConnectTimeout(10000);
  return connection;
}

代码示例来源: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: spring-projects/spring-security-oauth

@Override
protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
 HttpURLConnection connection = (HttpURLConnection) super.openConnection(url, proxy);
 connection.setRequestMethod(this.httpMethod);
 if (resourceDetails.isAcceptsAuthorizationHeader()) {
  String authHeader = support.getAuthorizationHeader(resourceDetails, accessToken, url, httpMethod, additionalParameters);
  connection.setRequestProperty("Authorization", authHeader);
 }
 return connection;
}

代码示例来源:origin: jmdhappy/xxpay-master

/**
 * 设置http请求默认属性
 *
 * @param httpConnection
 */
protected void setHttpRequest(HttpURLConnection httpConnection) {
  //设置连接超时时间
  httpConnection.setConnectTimeout(this.timeOut * 1000);
  //User-Agent
  httpConnection.setRequestProperty("User-Agent",
      HttpClient.USER_AGENT_VALUE);
  //不使用缓存
  httpConnection.setUseCaches(false);
  //允许输入输出
  httpConnection.setDoInput(true);
  httpConnection.setDoOutput(true);
}

代码示例来源: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: jenkinsci/jenkins

URL url = new URL(ENDPOINT);
  URLConnection conn = ProxyConfiguration.open(url);
  if (!(conn instanceof HttpURLConnection)) {
  http.setRequestProperty("Content-Type", "application/json; charset=utf-8");
  http.setDoOutput(true);
  try (OutputStream out = http.getOutputStream();
      OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
    writer.append(body);
  LOGGER.config("Telemetry submission received response '" + http.getResponseCode() + " " + http.getResponseMessage() + "' for: " + telemetry.getId());
} catch (MalformedURLException e) {
  LOGGER.config("Malformed endpoint URL: " + ENDPOINT + " for telemetry: " + telemetry.getId());

代码示例来源:origin: TeamNewPipe/NewPipe

/**
 * Open connection
 *
 * @param threadId   id of the calling thread, used only for debug
 * @param rangeStart range start
 * @param rangeEnd   range end
 * @return a {@link java.net.URLConnection URLConnection} linking to the URL.
 * @throws IOException if an I/O exception occurs.
 */
HttpURLConnection openConnection(int threadId, long rangeStart, long rangeEnd) throws IOException {
  URL url = new URL(urls[current]);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setInstanceFollowRedirects(true);
  if (rangeStart >= 0) {
    String req = "bytes=" + rangeStart + "-";
    if (rangeEnd > 0) req += rangeEnd;
    conn.setRequestProperty("Range", req);
    if (DEBUG) {
      Log.d(TAG, threadId + ":" + conn.getRequestProperty("Range"));
    }
  }
  return conn;
}

代码示例来源:origin: facebook/facebook-android-sdk

private static HttpURLConnection createConnection(URL url) throws IOException {
  HttpURLConnection connection;
  connection = (HttpURLConnection) url.openConnection();
  connection.setRequestProperty(USER_AGENT_HEADER, getUserAgent());
  connection.setRequestProperty(ACCEPT_LANGUAGE_HEADER, Locale.getDefault().toString());
  connection.setChunkedStreamingMode(0);
  return connection;
}

代码示例来源:origin: spring-projects/spring-framework

connection.setDoOutput(true);
connection.setRequestMethod(HTTP_METHOD_POST);
connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, getContentType());
connection.setRequestProperty(HTTP_HEADER_CONTENT_LENGTH, Integer.toString(contentLength));
  Locale locale = localeContext.getLocale();
  if (locale != null) {
    connection.setRequestProperty(HTTP_HEADER_ACCEPT_LANGUAGE, locale.toLanguageTag());
  connection.setRequestProperty(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);

代码示例来源:origin: spring-projects/spring-security-oauth

@Override
protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
 HttpURLConnection connection = (HttpURLConnection) super.openConnection(url, proxy);
 connection.setRequestMethod(this.httpMethod);
 if (resourceDetails.isAcceptsAuthorizationHeader()) {
  String authHeader = support.getAuthorizationHeader(resourceDetails, accessToken, url, httpMethod, additionalParameters);
  connection.setRequestProperty("Authorization", authHeader);
 }
 return connection;
}

代码示例来源:origin: stanfordnlp/CoreNLP

public boolean checkStatus(URL serverURL) {
 try {
  // 1. Set up the connection
  HttpURLConnection connection = (HttpURLConnection) serverURL.openConnection();
  // 1.1 Set authentication
  if (apiKey != null && apiSecret != null) {
   String userpass = apiKey + ':' + apiSecret;
   String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
   connection.setRequestProperty("Authorization", basicAuth);
  }
  connection.setRequestMethod("GET");
  connection.connect();
  return connection.getResponseCode() >= 200 && connection.getResponseCode() <= 400;
 } catch (Throwable t) {
  throw new RuntimeException(t);
 }
}

代码示例来源:origin: org.springframework/spring-web

connection.setDoOutput(true);
connection.setRequestMethod(HTTP_METHOD_POST);
connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, getContentType());
connection.setRequestProperty(HTTP_HEADER_CONTENT_LENGTH, Integer.toString(contentLength));
  Locale locale = localeContext.getLocale();
  if (locale != null) {
    connection.setRequestProperty(HTTP_HEADER_ACCEPT_LANGUAGE, locale.toLanguageTag());
  connection.setRequestProperty(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);

代码示例来源: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();
}

相关文章

HttpURLConnection类方法