欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java发送post方法详解

程序员文章站 2024-02-23 12:42:52
总结一下java使用http发送post的方法: 1、post请求用于发送json 格式的参数: /** * post请求(用于请求json格式的参数)...

总结一下java使用http发送post的方法:

1、post请求用于发送json 格式的参数:

/**
   * post请求(用于请求json格式的参数)
   *
   * @param url  地址
   * @param params json格式的参数
   * @return
   */
  public static string dopost(string url, string params) throws exception {
 
    closeablehttpclient httpclient = httpclients.createdefault();
    httppost httppost = new httppost( url );// 创建httppost
    httppost.setheader( "accept", "application/json" );
    httppost.setheader( "content-type", "application/json" );
    string charset = "utf-8";
    stringentity entity = new stringentity( params, charset );
    httppost.setentity( entity );
    closeablehttpresponse response = null;
 
    try {
 
      response = httpclient.execute( httppost );
      statusline status = response.getstatusline();
      int state = status.getstatuscode();
      if (state == httpstatus.sc_ok) {
        httpentity responseentity = response.getentity();
        string jsonstring = entityutils.tostring( responseentity );
        return jsonstring;
      } else {
        logger.error( "请求返回:" + state + "(" + url + ")" );
      }
    } finally {
      if (response != null) {
        try {
          response.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
      try {
        httpclient.close();
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
    return null;
  }

2、用于发送key-value格式的参数

/**
   * post请求(用于key-value格式的参数)
   *
   * @param url
   * @param params
   * @return
   */
  public static string dopost(string url, map params) {
 
    bufferedreader in = null;
    try {
      // 定义httpclient
      httpclient client = new defaulthttpclient();
      // 实例化http方法
      httppost request = new httppost();
      request.seturi( new uri( url ) );
 
      //设置参数
      list<namevaluepair> nvps = new arraylist<namevaluepair>();
      for (iterator iter = params.keyset().iterator(); iter.hasnext(); ) {
        string name = (string) iter.next();
        string value = string.valueof( params.get( name ) );
        nvps.add( new basicnamevaluepair( name, value ) );
 
        //system.out.println(name +"-"+value);
      }
      request.setentity( new urlencodedformentity( nvps, http.utf_8 ) );
 
      httpresponse response = client.execute( request );
      int code = response.getstatusline().getstatuscode();
      if (code == 200) {  //请求成功
        in = new bufferedreader( new inputstreamreader( response.getentity()
            .getcontent(), "utf-8" ) );
        stringbuffer sb = new stringbuffer( "" );
        string line = "";
        string nl = system.getproperty( "line.separator" );
        while ((line = in.readline()) != null) {
          sb.append( line + nl );
        }
        in.close();
 
        return sb.tostring();
      } else {  //
        system.out.println( "状态码:" + code );
        return null;
      }
    } catch (exception e) {
      e.printstacktrace();
      return null;
    }
  }

第三,发送get请求

/**
   * get请求
   *
   * @return
   */
  public static string doget(string url) {
    try {
      httpclient client = new defaulthttpclient();
      //发送get请求
      httpget request = new httpget( url );
      httpresponse response = client.execute( request );
      /**请求发送成功,并得到响应**/
      if (response.getstatusline().getstatuscode() == httpstatus.sc_ok) {
        /**读取服务器返回过来的json字符串数据**/
        string strresult = entityutils.tostring( response.getentity() );
        return strresult;
      }
    } catch (ioexception e) {
      e.printstacktrace();
    }
 
    return null;
  }

以上所述是小编给大家介绍的java发送post方法详解整合,希望对大家有所帮助