一个标准的java http请求和回应

一个标准的java http请求和回应
URL url = new URL("提交的URL");
 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 try
 {
  connection.setDoInput(true);
  connection.setDoOutput(true);
  {
   // 提交的内容
   byte[] requsetContent = new byte[1024];
   connection.setRequestProperty("Content-Length", Integer.toString(requsetContent.length));
   OutputStream outputStream = connection.getOutputStream();
   try
   {
    // 向外输入流
    outputStream.write(requsetContent);
    outputStream.flush();
   }
   catch (Exception ex)
   {
    throw ex;
   }
   finally
   {
    outputStream.close();
   }
  }
  // 获取HTTP相应请求
  int responseCode = connection.getResponseCode();
  String responseMessage = connection.getResponseMessage();
  {
   ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 64);
   // 得到返回流
   InputStream inputStream = connection.getInputStream();
   try
   {
    byte[] buf = new byte[1024 * 64];
    int n;
    while ((n = inputStream.read(buf)) >= 0)
    {
     baos.write(buf, 0, n);
    }
   }
   catch (Exception ex)
   {
    ex.printStackTrace();
   }
   finally
   {
    inputStream.close();
   }
   // 获取包的内容
   byte[] responseContent = baos.toByteArray();
  }
 }
 catch (Exception ex)
 {
  throw ex;
 }
 finally
 {
  connection.disconnect();
 }

你可能感兴趣的:(一个标准的java http请求和回应)