发布日期:2018-03-26
如何使用Java通过POST方法轻松发送HTTP请求并带参数?+ 查看更多
如何使用Java通过POST方法轻松发送HTTP请求并带参数?
+ 查看更多
发布日期:2018-03-08 17:23
分类:JAVA
浏览次数:221
我成功地使用此代码通过GET方法发送带有一些参数的HTTP请求:
function 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 ); }