`
han0332217
  • 浏览: 5737 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

[JAVA]使用HttpURLConnection进行POST方式提交

阅读更多
[JAVA]使用HttpURLConnection进行POST方式提交
--sunfruit

用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);

当然如果不设置的话,可以走默认值,上面的例子中就没有进行相关设置,但是也可以正确执行

分享到:
评论
1 楼 sosyi 2010-08-09  
多个参数 怎么该什么写??
String username="username=02000001";
httpurlconnection.getOutputStream().write(username.getBytes());

相关推荐

Global site tag (gtag.js) - Google Analytics