首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Java发送HTTP POST请求

使用Java发送HTTP POST请求
EN

Stack Overflow用户
提问于 2010-07-24 18:28:11
回答 11查看 888.1K关注 0票数 332

让我们假设这个URL...

代码语言:javascript
复制
http://www.example.com/page.php?id=10            

(这里的id需要在POST请求中发送)

我希望将id = 10发送到服务器的page.php,它在POST方法中接受它。

我如何在Java中做到这一点?

我试过这个:

代码语言:javascript
复制
URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();

但我还是想不出怎么邮寄

EN

回答 11

Stack Overflow用户

发布于 2010-07-24 20:25:14

更新答案:

由于原始答案中的一些类在较新版本的Apache HTTP组件中已被弃用,因此我在此发布此更新。

顺便说一句,您可以访问更多示例here的完整文档。

代码语言:javascript
复制
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

if (entity != null) {
    try (InputStream instream = entity.getContent()) {
        // do something useful
    }
}

原始答案:

我推荐使用Apache HttpClient。它更快、更容易实现。

代码语言:javascript
复制
HttpPost post = new HttpPost("http://jakarata.apache.org/");
NameValuePair[] data = {
    new NameValuePair("user", "joe"),
    new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.

有关更多信息,请查看此url:http://hc.apache.org/

票数 367
EN

Stack Overflow用户

发布于 2016-01-26 19:59:17

在vanilla Java中,发送POST请求很容易。从URL开始,我们需要使用url.openConnection();将其转换为URLConnection。之后,我们需要将它转换为HttpURLConnection,这样我们就可以访问它的setRequestMethod()方法来设置我们的方法。最后,我们说我们将通过连接发送数据。

代码语言:javascript
复制
URL url = new URL("https://www.example.com/login");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod("POST"); // PUT is another valid option
http.setDoOutput(true);

然后我们需要说明我们要发送的内容:

发送一个简单的表单

来自http表单的普通POST具有well defined格式。我们需要将输入转换为以下格式:

代码语言:javascript
复制
Map<String,String> arguments = new HashMap<>();
arguments.put("username", "root");
arguments.put("password", "sjh76HSn!"); // This is a fake password obviously
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
    sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" 
         + URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;

然后,我们可以将表单内容附加到具有适当标头的http请求并发送它。

代码语言:javascript
复制
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
    os.write(out);
}
// Do something with http.getInputStream()

发送JSON

我们也可以使用java发送json,这也很简单:

代码语言:javascript
复制
byte[] out = "{\"username\":\"root\",\"password\":\"password\"}" .getBytes(StandardCharsets.UTF_8);
int length = out.length;

http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
    os.write(out);
}
// Do something with http.getInputStream()

请记住,不同的服务器接受不同的json内容类型,请参阅this问题。

使用java post发送文件

发送文件可以被认为是更具挑战性的处理,因为格式更复杂。我们还将添加对以字符串形式发送文件的支持,因为我们不希望将文件完全缓冲到内存中。

为此,我们定义了一些助手方法:

代码语言:javascript
复制
private void sendFile(OutputStream out, String name, InputStream in, String fileName) {
    String o = "Content-Disposition: form-data; name=\"" + URLEncoder.encode(name,"UTF-8") 
             + "\"; filename=\"" + URLEncoder.encode(filename,"UTF-8") + "\"\r\n\r\n";
    out.write(o.getBytes(StandardCharsets.UTF_8));
    byte[] buffer = new byte[2048];
    for (int n = 0; n >= 0; n = in.read(buffer))
        out.write(buffer, 0, n);
    out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}

private void sendField(OutputStream out, String name, String field) {
    String o = "Content-Disposition: form-data; name=\"" 
             + URLEncoder.encode(name,"UTF-8") + "\"\r\n\r\n";
    out.write(o.getBytes(StandardCharsets.UTF_8));
    out.write(URLEncoder.encode(field,"UTF-8").getBytes(StandardCharsets.UTF_8));
    out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}

然后我们可以使用这些方法来创建一个多部分的post请求,如下所示:

代码语言:javascript
复制
String boundary = UUID.randomUUID().toString();
byte[] boundaryBytes = 
           ("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8);
byte[] finishBoundaryBytes = 
           ("--" + boundary + "--").getBytes(StandardCharsets.UTF_8);
http.setRequestProperty("Content-Type", 
           "multipart/form-data; charset=UTF-8; boundary=" + boundary);

// Enable streaming mode with default settings
http.setChunkedStreamingMode(0); 

// Send our fields:
try(OutputStream out = http.getOutputStream()) {
    // Send our header (thx Algoman)
    out.write(boundaryBytes);

    // Send our first field
    sendField(out, "username", "root");

    // Send a seperator
    out.write(boundaryBytes);

    // Send our second field
    sendField(out, "password", "toor");

    // Send another seperator
    out.write(boundaryBytes);

    // Send our file
    try(InputStream file = new FileInputStream("test.txt")) {
        sendFile(out, "identification", file, "text.txt");
    }

    // Finish the request
    out.write(finishBoundaryBytes);
}


// Do something with http.getInputStream()
票数 227
EN

Stack Overflow用户

发布于 2010-07-24 19:49:02

代码语言:javascript
复制
String rawData = "id=10";
String type = "application/x-www-form-urlencoded";
String encodedData = URLEncoder.encode( rawData, "UTF-8" ); 
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());
票数 108
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3324717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档