java使用httpclient发送post请求示例

所属分类: 软件编程 / java 阅读数: 52
收藏 0 赞 0 分享

复制代码 代码如下:

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;
 }
}

更多精彩内容其他人还在看

SpringBoot中使用Ehcache的详细教程

EhCache 是一个纯 Java 的进程内缓存框架,具有快速、精干等特点,是 Hibernate 中默认的 CacheProvider。这篇文章主要介绍了SpringBoot中使用Ehcache的相关知识,需要的朋友可以参考下
收藏 0 赞 0 分享

在idea 中添加和删除模块Module操作

这篇文章主要介绍了在idea 中添加和删除模块Module操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

java spring整合junit操作(有详细的分析过程)

这篇文章主要介绍了java spring整合junit操作(有详细的分析过程),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解JAVA 弱引用

这篇文章主要介绍了 JAVA 弱引用的相关资料,帮助大家更好的理解和学习java引用对象,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

深入了解JAVA 虚引用

这篇文章主要介绍了JAVA 虚引用的相关资料,帮助大家更好的理解和学习JAVA,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

详解JAVA 强引用

这篇文章主要介绍了JAVA 强引用的相关资料,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

java中的按位与(&)用法说明

这篇文章主要介绍了java中的按位与(&)用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

深入了解JAVA 软引用

这篇文章主要介绍了JAVA 软引用的相关资料,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

利用MyBatis实现条件查询的方法汇总

这篇文章主要给大家介绍了关于利用MyBatis实现条件查询的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者使用MyBatis具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
收藏 0 赞 0 分享

Intellij IDEA 与maven 版本不符 Unable to import maven project See logs for details: No implementation for org.apache.maven.model.path.PathTranslator was bound

这篇文章主要介绍了Intellij IDEA 与maven 版本不符 Unable to import maven project See logs for details: No implementation for org.apache.maven.model.path.Pa
收藏 0 赞 0 分享
查看更多