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

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

public class HttpConnectionPostTest {

    public static void main(String[] args) throws Exception {
    //设置代理,公司用的是代理上网
    System.setProperty("proxySet", "true");
        System.setProperty("proxyHost", "172.31.1.246");
        System.setProperty("proxyPort", "8080");
        //读取http://marc.info/?l=ant-dev&r=1&w=2的html输出
    URL url = new URL("http://marc.info/");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setDoOutput(true); // POST方式
    con.setRequestMethod("POST");
    OutputStream os = con.getOutputStream(); // 输出流,写数据
    os.write("l=ant-dev&r=1&w=2".getBytes());
   
    InputStream in = con.getInputStream(); // 读取结果
    OutputStream out = new BufferedOutputStream(getOutputStream());
    byte[] buf = new byte[2048];
    int c = -1;
    while ((c = in.read(buf)) != -1) {
        out.write(buf, 0, c);
    }
    out.flush();
    out.close();
    in.close();
    }
   
    private static OutputStream getOutputStream() throws Exception {
             return new FileOutputStream(new File("connection.html"));
    }
}

猜你喜欢

转载自vvsongsunny.iteye.com/blog/1109573