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

java使用httpclient发送post请求示例

程序员文章站 2024-02-21 18:21:16
复制代码 代码如下:package org.ssi.util; import java.io.ioexception;import java.util.arraylist...

复制代码 代码如下:

package org.ssi.util;

import java.io.ioexception;
import java.util.arraylist;
import java.util.list;

import net.sf.json.jsonarray;

import org.apache.commons.lang.exception.exceptionutils;
import org.apache.commons.logging.log;
import org.apache.commons.logging.logfactory;
import org.apache.http.httpresponse;
import org.apache.http.httpstatus;
import org.apache.http.namevaluepair;
import org.apache.http.client.httpclient;
import org.apache.http.client.entity.urlencodedformentity;
import org.apache.http.client.methods.httppost;
import org.apache.http.impl.client.defaulthttpclient;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.protocol.http;
import org.apache.http.util.entityutils;


public class apihttpclient {

 //接口地址
 private string apiurl = "";
 private log logger = logfactory.getlog(this.getclass());
 private static final string pattern = "yyyy-mm-dd hh:mm:ss:sss";
        private httpclient httpclient = null;
 private httppost method = null;
 private long starttime = 0l;
 private long endtime = 0l;
 private int status = 0;
 /**
  * 接口地址
  * @param url
  */
 public apihttpclient(string url){

  if(url != null)
  {
   this.apiurl = url;
  }
  if(apiurl != null)
  {
                    httpclient = new defaulthttpclient();
                    method = new httppost(apiurl);

  }
 }

 /**
  * 调用 api
  * @param parameters
  * @return
  */
 public string post(string parameters)
 {
  string body = null;
                logger.info("parameters:" + parameters);

               
  if(method != null & parameters != null  && !"".equals(parameters.trim()))
  {
                    jsonarray jsonobject = jsonarray.fromobject(parameters);
                    logger.info("json:" + jsonobject.tostring());
                    try{

                        list<namevaluepair> params=new arraylist<namevaluepair>(); 
                        //建立一个namevaluepair数组,用于存储欲传送的参数 
                        params.add(new basicnamevaluepair("data",parameters)); 
                        //添加参数 
                        method.setentity(new urlencodedformentity(params,http.utf_8)); 

                        starttime = system.currenttimemillis();

                        //设置编码 
                        httpresponse response=httpclient.execute(method); 
                        endtime = system.currenttimemillis();
                        int statuscode = response.getstatusline().getstatuscode();
                        logger.info("statuscode:" + statuscode);
                         logger.info("调用api 花费时间(单位:毫秒):" + (endtime - starttime));
                        if(statuscode != httpstatus.sc_ok){
                            logger.error("method failed:"+response.getstatusline());
                            status = 1;
                        }

                            //read the response body
                             body=entityutils.tostring(response.getentity());

   }catch(ioexception e){
    //发生网络异常
    logger.error("exception occurred!\n"+exceptionutils.getfullstacktrace(e));
    //网络错误
    status = 3;
   }
                    finally{
                        logger.info("调用接口状态:" + status);
                    }

   
  }
  return body;
 }

 /**
  * 0.成功 1.执行方法失败 2.协议错误 3.网络错误
  * @return the status
  */
 public int getstatus() {
  return status;
 }

 /**
  * @param status the status to set
  */
 public void setstatus(int status) {
  this.status = status;
 }
 /**
  * @return the starttime
  */
 public long getstarttime() {
  return starttime;
 }
 /**
  * @return the endtime
  */
 public long getendtime() {
  return endtime;
 }
}