4.8 通过POST方法轻松发送HTTP参数| Java Debug 笔记

本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看<活动链接>

提问:通过POST方法轻松发送HTTP参数

我成功地使用此代码完成HTTP通过GET方法发送带有某些参数的请求的功能。

void sendRequest(String request)
{
    // i.e.: request = "http://example.com/index.php?param1=a&param2=b&param3=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");
复制代码

改为

connction.setRequestMethod("POST");

复制代码

仍旧可以完成上述功能,但是参数还是用Get传送的

HttpURLConnection类有方法可以帮助我吗?Java有能帮助我实现目的的结构体吗?

回答1:

在GET请求中,参数作为URL的一部分发送。

在POST请求中,将参数作为请求的正文发送到标头之后。

要使用HttpURLConnection进行POST,您需要在打开连接后将参数写入连接。

以下代码可以让你理解这部分知识:

String urlParameters  = "param1=a&param2=b&param3=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 );
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享