我已成功使用此代码通过 GET
方法发送带有一些参数的 HTTP
请求
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)。
如何尽可能少地更改上面的代码,以便能够通过 GET
或 POST
发送参数?
我希望改变
connection.setRequestMethod("GET");
到
connection.setRequestMethod("POST");
本来可以,但参数仍然通过 GET 方法发送。
HttpURLConnection
有什么方法有用吗?
有什么有用的 Java 构造吗?
非常感谢任何帮助。
最佳答案
在 GET 请求中,参数作为 URL 的一部分发送。
在 POST 请求中,参数作为请求正文发送,位于请求头之后。
要使用 HttpURLConnection 进行 POST,您需要在打开连接后将参数写入连接。
此代码应该可以帮助您入门:
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 );
}
https://stackoverflow.com/questions/4205980/