在Java中发送HTTP POST请求

在Java中发送HTTP POST请求,java,http,post,Java,Http,Post,让我们假设这个URL http://www.example.com/page.php?id=10 (此处需要在POST请求中发送id) 我想将id=10发送到服务器的page.php,它通过POST方法接受它 如何在Java中实现这一点 我试过这个: URL aaa = new URL("http://www.example.com/page.php"); URLConnection ccc = aaa.openConnection(); 但是我仍然不知道如何通过PO

让我们假设这个URL

http://www.example.com/page.php?id=10            
(此处需要在POST请求中发送id)

我想将
id=10
发送到服务器的
page.php
,它通过POST方法接受它

如何在Java中实现这一点

我试过这个:

URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();

但是我仍然不知道如何通过POST调用
HttpURLConnection.setRequestMethod(“POST”)
HttpURLConnection.setDoOutput(true)发送它实际上只需要后者,因为POST随后成为默认方法。

更新答案:
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());
由于原始答案中的某些类在较新版本的ApacheHTTP组件中被弃用,因此我发布了此更新

顺便说一下,您可以访问完整的文档以获取更多示例


有关更多信息,请查看此url:

第一个答案很好,但我必须添加try/catch以避免Java编译器错误。
此外,我还很难理解如何使用Java库读取
HttpResponse

以下是更完整的代码:

/*
 * Create the POST request
 */
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
}
/*
 * Execute the HTTP Request
 */
try {
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity respEntity = response.getEntity();

    if (respEntity != null) {
        // EntityUtils to get the response content
        String content =  EntityUtils.toString(respEntity);
    }
} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}
/*
*创建POST请求
*/
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://example.com/");
//请求参数和其他属性。
List params=new ArrayList();
添加参数(新的BasicNameValuePair(“用户”、“Bob”);
试一试{
setEntity(新的UrlEncodedFormEntity(参数,“UTF-8”);
}捕获(不支持的编码异常e){
//将错误写入日志
e、 printStackTrace();
}
/*
*执行HTTP请求
*/
试一试{
HttpResponse response=httpClient.execute(httpPost);
HttpEntity respEntity=response.getEntity();
if(respEntity!=null){
//EntityUtils以获取响应内容
字符串内容=EntityUtils.toString(respEntity);
}
}捕获(客户端协议例外e){
//将异常写入日志
e、 printStackTrace();
}捕获(IOE异常){
//将异常写入日志
e、 printStackTrace();
}

使用Apache HTTP组件的简单方法是

Request.Post("http://www.example.com/page.php")
            .bodyForm(Form.form().add("id", "10").build())
            .execute()
            .returnContent();

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

URL=新URL(“https://www.example.com/login");
URLConnection con=url.openConnection();
HttpURLConnection http=(HttpURLConnection)con;
http.setRequestMethod(“POST”);//看跌期权是另一个有效的选择
http.setDoOutput(true);
然后,我们需要说明我们将发送什么:

发送简单表单 来自http表单的普通POST具有一种格式。我们需要将输入转换为以下格式:

Map参数=newhashmap();
参数。put(“用户名”、“根”);
参数。put(“密码”,“sjh76HSn!”);//这显然是一个假密码
细木工sj=新细木工(&);
for(Map.Entry:arguments.entrySet())
sj.add(URLEncoder.encode(entry.getKey(),“UTF-8”)+“=”
+encode(entry.getValue(),“UTF-8”);
byte[]out=sj.toString().getBytes(StandardCharsets.UTF_8);
int长度=out.length;
然后,我们可以使用适当的头将表单内容附加到http请求并发送它

http.setFixedLengthStreamingMode(长度);
http.setRequestProperty(“内容类型”,“应用程序/x-www-form-urlencoded;字符集=UTF-8”);
http.connect();
尝试(OutputStream os=http.getOutputStream()){
o.写(出);
}
//使用http.getInputStream()执行一些操作

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

byte[]out=“{\”用户名\“:\”根\“,\”密码\“:\”密码\“}”。getBytes(StandardCharsets.UTF\u 8);
int长度=out.length;
http.setFixedLengthStreamingMode(长度);
setRequestProperty(“内容类型”,“应用程序/json;字符集=UTF-8”);
http.connect();
尝试(OutputStream os=http.getOutputStream()){
o.写(出);
}
//使用http.getInputStream()执行一些操作
请记住,不同的服务器接受不同的json内容类型,请参阅问题


用javapost发送文件 由于格式更复杂,发送文件可能会被认为更难处理。我们还将添加对以字符串形式发送文件的支持,因为我们不希望将文件完全缓冲到内存中

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

private void sendFile(输出流输出、字符串名称、输入流输入、字符串文件名){
String o=“内容处置:表单数据;名称=\”“+urlcoder.encode(名称,“UTF-8”)
+“\”文件名=\”+URLEncoder.encode(文件名,“UTF-8”)+“\”\r\n\r\n”;
out.write(o.getBytes(StandardCharsets.UTF_8));
字节[]缓冲区=新字节[2048];
用于(int n=0;n>=0;n=in.read(缓冲区))
out.write(缓冲区,0,n);
out.write(“\r\n”.getBytes(StandardCharsets.UTF_8));
}
私有void sendField(OutputStream out、字符串名称、字符串字段){
String o=“内容处置:表单数据;名称=\”“
+URLEncoder.encode(名称,“UTF-8”)+“\”\r\n\r\n”;
out.write(o.getBytes(StandardCharsets.UTF_8));
out.write(URLEncoder.encode(字段,“UTF-8”).getBytes(StandardCharsets.UTF_8));
out.write(“\r\n”.getBytes(StandardCharsets.UTF_8));
}
然后,我们可以使用这些方法创建多部分post请求,如下所示:

String boundary=UUID.randomUUID().toString();
字节[]边界字节=
(“-”+boundary+“\r\n”).getBytes(StandardCharsets.UTF_8);
字节[]finishBoundaryBytes=
(“-”+边界+“-”).getBytes(StandardCharsets.UTF_8);
http.setRequestProperty(“内容类型”,
“多部分/表单数据;字符集=UTF-8;边界=”+边界);
//使用默认设置启用流模式
http.setChunkedStreamingM
/*
 * Create the POST request
 */
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
}
/*
 * Execute the HTTP Request
 */
try {
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity respEntity = response.getEntity();

    if (respEntity != null) {
        // EntityUtils to get the response content
        String content =  EntityUtils.toString(respEntity);
    }
} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}
Request.Post("http://www.example.com/page.php")
            .bodyForm(Form.form().add("id", "10").build())
            .execute()
            .returnContent();
String postURL = "http://www.example.com/page.php";

HttpPost post = new HttpPost(postURL);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "10"));

UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(ent);

HttpClient client = new DefaultHttpClient();
HttpResponse responsePOST = client.execute(post);
BufferedReader reader = new BufferedReader(new  InputStreamReader(responsePOST.getEntity().getContent()), 2048);

if (responsePOST != null) {
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(" line : " + line);
        sb.append(line);
    }
    String getResponseString = "";
    getResponseString = sb.toString();
//use server output getResponseString as string value.
}
HttpRequest<String> httpRequest = HttpRequestBuilder.createPost("http://www.example.com/page.php", String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();

public void send(){
   String response = httpRequest.execute("id", "10").get();
}