用HttpURLConnection进行Post方式提交,下面给出一个例子
URL url = null;
HttpURLConnection httpurlconnection = null;
try
{
url = new URL("http://xxxx");
httpurlconnection = (HttpURLConnection) url.openConnection();
httpurlconnection.setDoOutput(true);
httpurlconnection.setRequestMethod("POST");
String username="username=02000001";
httpurlconnection.getOutputStream().write(username.getBytes());
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
int code = httpurlconnection.getResponseCode();
System.out.println("code " + code);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(httpurlconnection!=null)
httpurlconnection.disconnect();
}
其中HttpURLConnection中的addRequestProperty方法,并不是用来添加Parameter 的,而是用来设置请求的头信息,比如:
setRequestProperty("Content-type","text/html");
setRequestProperty("Connection", "close");
setRequestProperty("Content-Length",xxx);
当然如果不设置的话,可以走默认值,上面的例子中就没有进行相关设置,但是也可以正确执行
使用HttpURLConnection进行POST方式提交
最新推荐文章于 2021-03-26 11:11:07 发布
本文详细介绍了如何使用HttpURLConnection进行Post方式提交,并通过示例代码展示了关键步骤,包括设置URL、创建连接、设置请求方法和参数。此外,文章还强调了addRequestProperty方法的作用并非用于添加参数,而是用于设置请求头信息。
8383

被折叠的 条评论
为什么被折叠?



