Java调用Http处理数据(post和get)

/**
   * @param url:请求url
   * @param content:  请求体(参数)
   * @return errorStr:错误信息;status:状态码,response:返回数据
   */
  public Map<String,Object> requestPost(String url, String content){
    Map<String,Object> result = new HashMap<String,Object>();
    String errorStr = "";
    String status = "";
    String response = "";
    PrintWriter out = null;
    BufferedReader in = null;
    try {
      URL realUrl = new URL(url);
      // 打开和URL之间的连接
      URLConnection conn = realUrl.openConnection();
      HttpURLConnection httpUrlConnection = (HttpURLConnection)conn;
      // 设置请求属性
      httpUrlConnection.setRequestProperty("Content-Type", "application/json");
      // 发送POST请求必须设置如下两行
      httpUrlConnection.setDoOutput(true);
      httpUrlConnection.setDoInput(true);
      // 获取URLConnection对象对应的输出流
      out = new PrintWriter(httpUrlConnection.getOutputStream());
      // 发送请求参数
      out.write(content);
      // flush输出流的缓冲
      out.flush();
      httpUrlConnection.connect();
      // 定义BufferedReader输入流来读取URL的响应
      in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
      String line;
      while((line = in.readLine())!=null){
        response += line;
      }
      status = new Integer(httpUrlConnection.getResponseCode()).toString();
    } catch(Exception e){
      System.out.println("发送 POST 请求出现异常!"+e);
      errorStr = e.getMessage();
    }
    // 使用finally块来关闭输出流、输入流
    finally{
      try {
        if(out!=null){
          out.close();
        }
        if(in!=null){
          in.close();
        }
      } catch(Exception ex){
        ex.printStackTrace();
      }
    }

    result.put("errorStr", errorStr);
    result.put("response", response);
    result.put("status", status);
    return result;
  }
public Map<String,Object> requestGet(TdmachineConfig tdmachineConfig, Map<Object,Object> params){
    log.info("========>Get请求");
    Map<String,Object> result = new HashMap<String,Object>();
    String errorStr = "";
    String status = "";
    String response = "";
    String url = "http://"+tdmachineConfig.getIp()+":"+tdmachineConfig.getPort()+tdmachineConfig.getMethodPath();
    try {
      if(!params.isEmpty()){
        url = url+"?"+getUrlData(params);
      }
    } catch(Exception e){
      e.printStackTrace();
    }
    BufferedReader in = null;
    try {
      URL realUrl = new URL(url);
      // 打开和URL之间的连接
      URLConnection connection = realUrl.openConnection();
      // 设置通用的请求属性
      connection.setRequestProperty("accept", "*/*");
      connection.setRequestProperty("connection", "Keep-Alive");
      connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
      // 建立实际的连接
      connection.connect();
      // 获取所有响应头字段
      // 定义 BufferedReader输入流来读取URL的响应
      in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
      String line;
      while((line = in.readLine())!=null){
        response += line;
      }
    } catch(Exception e){
      log.info("发送 GET 请求出现异常!"+e);
      errorStr = e.getMessage();
    } finally{
      if(in!=null){
        try {
          in.close();
        } catch(Exception ex){
          ex.printStackTrace();
        }
      }
    }
    result.put("errorStr", errorStr);
    result.put("response", response);
    result.put("status", status);
    return result;
  }


  //将map型转为请求参数型
  public String getUrlData(Map<Object,Object> data) throws Exception{
    StringBuffer sb = new StringBuffer();
    try {
      Set<Map.Entry<Object,Object>> entries = data.entrySet();
      Iterator<Map.Entry<Object,Object>> iterators = entries.iterator();
      while(iterators.hasNext()){
        Map.Entry<Object,Object> next = iterators.next();
        sb.append(next.getKey().toString().trim()).append("=").append(URLEncoder.encode(next.getValue()+"", "UTF-8").trim()).append("&");
      }
      sb.deleteCharAt(sb.length()-1);
    } catch(Exception e){
      sb.append(e.toString());
    }
    return sb.toString();
  }
经验分享 程序员 微信小程序 职场和发展