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

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

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

HttpURLConnection.setRequestMethod介绍

[英]Sets the request command which will be sent to the remote HTTP server. This method can only be called before the connection is made.
[中]设置将发送到远程HTTP服务器的请求命令。只能在建立连接之前调用此方法。

代码示例

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: stackoverflow.com

HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("POST");
// ...

代码示例来源:origin: skylot/jadx

private static <T> T get(String url, Type type) throws IOException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    if (con.getResponseCode() == 200) {
      Reader reader = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8);
      return GSON.fromJson(reader, type);
    }
    return null;
  }
}

代码示例来源: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: stackoverflow.com

private int tryGetFileSize(URL url) {
   HttpURLConnection conn = null;
   try {
     conn = (HttpURLConnection) url.openConnection();
     conn.setRequestMethod("HEAD");
     conn.getInputStream();
     return conn.getContentLength();
   } catch (IOException e) {
     return -1;
   } finally {
     conn.disconnect();
   }
 }

代码示例来源:origin: stackoverflow.com

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

FileBody fileBody = new FileBody(new File(fileName));
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
multipartEntity.addPart("file", fileBody);

connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
OutputStream out = connection.getOutputStream();
try {
  multipartEntity.writeTo(out);
} finally {
  out.close();
}
int status = connection.getResponseCode();
...

代码示例来源:origin: stackoverflow.com

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
  // Not OK.
}

// < 100 is undetermined.
// 1nn is informal (shouldn't happen on a GET/HEAD)
// 2nn is success
// 3nn is redirect
// 4nn is client error
// 5nn is server error

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

private static HttpURLConnection makePreSignedRequest(String method, String preSignedUrl, Map headers) throws IOException {
  URL url = new URL(preSignedUrl);
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(method);
  addHeaders(connection, headers);
  return connection;
}

代码示例来源:origin: chewiebug/GCViewer

private FileInformation readFileInformation(URL url) {
  FileInformation fileInformation = new FileInformation();
  URLConnection urlConnection;
  try {
    if (url.getProtocol().startsWith("http")) {
      urlConnection = url.openConnection();
      ((HttpURLConnection) urlConnection).setRequestMethod("HEAD");
      try (InputStream inputStream = urlConnection.getInputStream()) {
        fileInformation.length = urlConnection.getContentLength();
        fileInformation.lastModified = urlConnection.getLastModified();
      }
    }
    else {
      if (url.getProtocol().startsWith("file")) {
        File file = new File(url.getFile());
        if (file.exists()) {
          fileInformation = new FileInformation(file);
        }
      }
    }
  }
  catch (IOException e) {
    if (LOG.isLoggable(Level.WARNING))
      LOG.log(Level.WARNING, "Failed to obtain age and length of URL " + url, e);
  }
  return fileInformation;
}

代码示例来源:origin: apache/storm

@Override
public void handleDataPoints(TaskInfo taskInfo, Collection<DataPoint> dataPoints) {
  try {
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    try (Output out = new Output(con.getOutputStream())) {
      serializer.serializeInto(Arrays.asList(taskInfo, dataPoints, topologyId), out);
      out.flush();
    }
    //The connection is not sent unless a response is requested
    int response = con.getResponseCode();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: stackoverflow.com

URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
  "Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();

代码示例来源:origin: apache/incubator-druid

@Test
 public void testBindOnHost() throws Exception
 {
  Assert.assertEquals("localhost", server.getURI().getHost());

  final URL url = new URL("http://localhost:" + port + "/default");
  final HttpURLConnection get = (HttpURLConnection) url.openConnection();
  Assert.assertEquals(DEFAULT_RESPONSE_CONTENT, IOUtils.toString(get.getInputStream(), StandardCharsets.UTF_8));

  final HttpURLConnection post = (HttpURLConnection) url.openConnection();
  post.setRequestMethod("POST");
  Assert.assertEquals(DEFAULT_RESPONSE_CONTENT, IOUtils.toString(post.getInputStream(), StandardCharsets.UTF_8));
 }
}

代码示例来源:origin: stackoverflow.com

URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
  httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();

代码示例来源:origin: apache/incubator-druid

@Test
public void testProxyGzipCompression() throws Exception
{
 final URL url = new URL("http://localhost:" + port + "/proxy/default");
 final HttpURLConnection get = (HttpURLConnection) url.openConnection();
 get.setRequestProperty("Accept-Encoding", "gzip");
 Assert.assertEquals("gzip", get.getContentEncoding());
 final HttpURLConnection post = (HttpURLConnection) url.openConnection();
 post.setRequestProperty("Accept-Encoding", "gzip");
 post.setRequestMethod("POST");
 Assert.assertEquals("gzip", post.getContentEncoding());
 final HttpURLConnection getNoGzip = (HttpURLConnection) url.openConnection();
 Assert.assertNotEquals("gzip", getNoGzip.getContentEncoding());
 final HttpURLConnection postNoGzip = (HttpURLConnection) url.openConnection();
 postNoGzip.setRequestMethod("POST");
 Assert.assertNotEquals("gzip", postNoGzip.getContentEncoding());
}

代码示例来源:origin: stackoverflow.com

HttpURLConnection httpUrlConnection = null;
URL url = new URL("http://example.com/server.cgi");
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setDoOutput(true);

httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
httpUrlConnection.setRequestProperty(
  "Content-Type", "multipart/form-data;boundary=" + this.boundary);

代码示例来源:origin: stackoverflow.com

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();

代码示例来源:origin: stackoverflow.com

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);

代码示例来源:origin: stackoverflow.com

String urlParameters  = "param1=a&param2=b&param3=c";
byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
int    postDataLength = postData.length;
String request        = "http://example.com/index.php";
URL    url            = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
  wr.write( postData );
}

代码示例来源:origin: stackoverflow.com

String rawData = "id=10";
String type = "application/x-www-form-urlencoded";
String encodedData = URLEncoder.encode( rawData ); 
URL u = new URL("http://www.example.com/page.php");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", String.valueOf(encodedData.length()));
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());

代码示例来源:origin: stackoverflow.com

URL url = new URL("http://www.example.com/login");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod("POST"); // PUT is another valid option
http.setDoOutput(true);

相关文章

HttpURLConnection类方法