java中两种发起POST请求,并接收返回的响应内容的方式  (转)

http://xyz168000.blog.163.com/blog/static/21032308201162293625569/

2、利用java自带的java.net.*包下提供的工具类

代码如下:

/**
  * 利用URL发起POST请求,并接收返回信息
  *
  * @param url 请求URL
  * @param message 请求参数
  * @return 响应内容
  */
 @Override
 public String transport(String url, String message) {
  StringBuffer sb = new StringBuffer();
  try {
   URL urls = new URL(url);
   HttpURLConnection uc = (HttpURLConnection) urls.openConnection();
   uc.setRequestMethod("POST");
   uc.setRequestProperty("content-type",
     "application/x-www-form-urlencoded");
   uc.setRequestProperty("charset", "UTF-8");
   uc.setDoOutput(true);
   uc.setDoInput(true);
   uc.setReadTimeout(10000);
   uc.setConnectTimeout(10000);
   OutputStream os = uc.getOutputStream();
   DataOutputStream dos = new DataOutputStream(os);
   dos.write(message.getBytes("utf-8"));
   dos.flush();
   os.close();
   BufferedReader in = new BufferedReader(new InputStreamReader(uc
     .getInputStream(), "utf-8"));
   String readLine = "";
   while ((readLine = in.readLine()) != null) {
    sb.append(readLine);
   }
   in.close();
  } catch (Exception e) {
   log.error(e.getMessage(), e);
  }
  return sb.toString();
 }

 

posted @ 2017-03-22 15:37  quietwalk  阅读(5605)  评论(0编辑  收藏  举报