问题描述
我成功地使用此代码通过GET
方法发送带有一些参数的HTTP
请求
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();
}
现在我可能需要通过 POST
方法发送参数(即 param1、param2、param3),因为它们很长.我想为该方法添加一个额外的参数(即 String 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 请求中,参数作为请求正文发送,在请求头之后.
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 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!