HttpPost 流的使用方法

来源:互联网 发布:点云建模软件 编辑:程序博客网 时间:2024/09/21 08:17

使用的jar包:

httpclient-4.3.2.jar
httpcore-4.3.1.jar
commons-logging-1.1.3.jar
commons-codec-1.6.jar

代码:


import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.honor.lottery.paymentservice.PaymentServiceImpl;

public class HttpPostService {
 private static final Logger logger = LoggerFactory
   .getLogger(PaymentServiceImpl.class);

 public String getResponse(String request, String url) {
  logger.info("PayRequest:" + request);
  String reStr = null;
  CloseableHttpClient httpClient = HttpClients.createDefault();
  HttpPost httpPost = null;
  CloseableHttpResponse httppHttpResponse2 = null;
  InputStreamEntity reqEntity = null;

  try {
   httpPost = new HttpPost(url);// 2互亿,http://106.ihuyi.cn/webservice/sms.php?method=Submit
   reqEntity = new InputStreamEntity(new ByteArrayInputStream(
     request.getBytes("utf-8")), -1);// 注意此处编码不一致
   httpPost.setEntity(reqEntity);

   httppHttpResponse2 = httpClient.execute(httpPost);

   if (httppHttpResponse2.getStatusLine().getStatusCode() == 200) {
    reStr = EntityUtils.toString(httppHttpResponse2.getEntity());
    logger.info("PayResponse" + reStr);
   }
   return reStr;
  } catch (Exception e) {
   logger.info(e.getMessage(), e);
   e.printStackTrace();
   return reStr;
  } finally {
   logger.info(reStr);
   try {
    if (httpPost != null) {
     httpPost.abort();
     httpPost = null;
    }
    if (httppHttpResponse2 != null) {
     httppHttpResponse2.close();
     httppHttpResponse2 = null;
    }
    if (httpClient != null) {
     httpClient.close();
     httpPost = null;
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

  }

 }

}




0 0