小编典典

Java-通过POST方法轻松发送HTTP参数

java

我成功使用此代码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");

connection.setRequestMethod("POST");

本来可以解决问题的,但是参数仍然通过GET方法发送。

HttpURLConnection没有什么方法会有所帮助?有没有有用的Java构造?

任何帮助将不胜感激。


阅读 388

收藏
2020-02-25

共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 );
}
2020-02-25