httpurlconectiondopost的方法向服务器中获取json文件

 public String getweb() {

  // 定义的返回值   String str1 = null;  

 StringBuffer sb = new StringBuffer();

  try {

   // new 一个路径  

  URL url = new URL(str);

   // 通过HttpURLConnection方法打开网络连接   

 HttpURLConnection con = (HttpURLConnection) url.openConnection();

   // 请求时间  

  con.setConnectTimeout(5000);

   // 读取时间    con.setReadTimeout(5000);

   // 设置成post方法    con.setRequestMethod("POST");   

 // 设置可写和可读    con.setDoInput(true);    con.setDoOutput(true);  

  // 判断返回值  

  if (con.getResponseCode() == 200) {   

  // 读取服务器中的文件     BufferedReader bu = new BufferedReader(new InputStreamReader(  con.getInputStream(), "utf-8"));

    // 定义一个string空     String name = null;  

   // 通过while循环读取文件   

  // 读取一次文件就把值付给name  

   // 判断name不等于空就把文件通过StringBuffer进行追加   

  // 追加是不把值覆盖而是向下追加   

  while ((name = bu.readLine()) != null) {  

    sb.append(name);      System.out.println(name);

    }  }

  } catch (Exception e) {  

  // TODO Auto-generated catch block   

 e.printStackTrace();

  }

  // 把读取到的文件返回去  

 return sb.toString();

 }

原文地址:https://www.cnblogs.com/3674-it/p/5106363.html