Java - 通过POST方法轻松发送HTTP参数 [英] Java - sending HTTP parameters via POST method easily
问题描述
我成功使用此代码通过 GET
方法
I am successfully using this code to send HTTP
requests with some parameters via GET
method
void sendRequest(String request)
{
// i.e.: request = "http://example.com/index.php?param1=a¶m2=b¶m3=c";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
}
现在我可能需要发送参数(即param1,param2,param3)通过 POST
方法,因为它们非常长。
我想在该方法中添加一个额外的参数(即字符串httpMethod)。
Now I may need to send the parameters (i.e. param1, param2, param3) via POST
method because they are very long.
I was thinking to add an extra parameter to that method (i.e. String httpMethod).
如何能够尽可能少地更改上面的代码才能够通过 GET
或 POST
发送参数?
How can I change the code above as little as possible to be able to send paramters either via GET
or POST
?
我希望改变
connection.setRequestMethod("GET");
到
connection.setRequestMethod("POST");
可以做到这一点,但参数仍然是通过GET方法发送的。
would have done the trick, but the parameters are still sent via GET method.
有 HttpURLConnection
有任何方法可以提供帮助吗?
是否有任何有用的Java构造?
Has HttpURLConnection
got any method that would help?
Is there any helpful Java construct?
非常感谢任何帮助。
推荐答案
在GET请求中,参数作为URL的一部分发送。
In a GET request, the parameters are sent as part of the URL.
在POST请求中,参数作为a请求的主体,在标题之后。
In a POST request, the parameters are sent as a body of the request, after the headers.
要使用HttpURLConnection执行POST,您需要在打开连接后将参数写入连接。
To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.
此代码可以帮助您入门:
This code should get you started:
String urlParameters = "param1=a¶m2=b¶m3=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 );
}
这篇关于Java - 通过POST方法轻松发送HTTP参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!