httpclient 4.0 与服务端交互

 有如下需求:使用httpclient向服务端发送xml文件,然后服务端收到信息后会做些判断,然后返回给客户端一些信息。

实现思路:利用httpclient post方法向服务端发送流文件,然后通过response获得返回值。代码中会涉及一些,最大连接次数等

具体代码如下:调用时先createentity ,post然后readdata,最后关闭

package iBank.util.communication;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;public class HttpClientUtil { private HttpClient httpclient = null;
 private HttpPost httppost = null;
 private InputStream in = null;
 private InputStreamEntity xmlEntity = null;
 private HttpResponse response = null;
 private HttpEntity resEntity = null;
 private InputStream inputStream = null;
 private String URL;
 private String filePath;
 private int nTimeout;// 连接超时设置
 private int nMaxRetry; // 最大重复次数 public HttpClientUtil() {
  httpclient = new DefaultHttpClient();
 } public void createInputStreamEntity() throws FileNotFoundException {
  File file = new File(filePath);
  in = new FileInputStream(file);
  xmlEntity = new InputStreamEntity(in, file.length());
 } /**
  * 功能: 关闭httpclient
  * 
  * @param 无
  * @return 无
  * @throws IOException
  * @throws 无
  */
 public void disConnect() {
  httpclient.getConnectionManager().shutdown();
 } /**
  * 功能: 以post方式发送请求
  * 
  * @param 无
  * @return 无
  * @throws 无
  */
 public boolean post() {
  int nCnt = 0; // 执行次数
  boolean rtn = false;  while (nCnt < nMaxRetry) {
   nCnt++;
   // 取得httppost
   httppost = new HttpPost(URL);
   // 请求超时
   httpclient.getParams().setParameter(
     CoreConnectionPNames.CONNECTION_TIMEOUT, nTimeout);
   // 读取超时
   httpclient.getParams().setParameter(
     CoreConnectionPNames.SO_TIMEOUT, nTimeout);
   // 写入报文信息
   httppost.setEntity(xmlEntity);
   httppost.setHeader("Content-Type", "application/xml;charset=utf-8");   try {
    response = httpclient.execute(httppost);
   } catch (IOException e) {
    System.out.println("connection timeout");
    continue;
   }
   //返回结果取得成功时,中断连接
   if (response.getStatusLine().getStatusCode() == 200) {
    rtn = true;
    break;
   }   try {
    response.getEntity().getContent().close();
   } catch (IOException e) {
    return false;
   }
  }  return rtn;
 } // 从服务器端读取数据
 public InputStream readData() throws IOException {
  resEntity = response.getEntity();
  inputStream = resEntity.getContent();
  return inputStream;
 } public String getURL() {
  return URL;
 } public void setURL(String url) {
  URL = url;
 }
 public int getNTimeout() {
  return nTimeout;
 } public void setNTimeout(int timeout) {
  nTimeout = timeout;
 } public int getNMaxRetry() {
  return nMaxRetry;
 } public void setNMaxRetry(int maxRetry) {
  nMaxRetry = maxRetry;
 } public String getFilePath() {
  return filePath;
 } public void setFilePath(String filePath) {
  this.filePath = filePath;
 }}


 

sever端为了测试我自己创建了一个简单的servlet项目,让上面客户端程序直接提交到服务端,然后读取返回信息。

server程序如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class Login extends HttpServlet { @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  doPost(req, resp);
 } @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  System.out.println("encoding:"+req.getCharacterEncoding());
  System.out.println("post");
  req.setCharacterEncoding("UTF-8");
  InputStream is = req.getInputStream();
  System.out.println("contenttype"+req.getContentType());
  resp.setContentType("application/xml;charset=utf-8");
  String isStr = "";
  StringBuilder sb = new StringBuilder();;
  try {
   isStr = convertStreamToString(is);
   sb.append(isStr);
   sb.append("i am back from server!");
  } catch (Exception e1) {
   e1.printStackTrace();
  }
  OutputStream out = resp.getOutputStream();
  OutputStreamWriter ouputw = new OutputStreamWriter(out,"UTF-8"); 
  String str2 = sb.toString();
  System.out.println("*********:"+str2);
  ouputw.write(str2);
  ouputw.flush();
  ouputw.close();
 }
 
 public static String convertStreamToString(InputStream is) throws Exception{
     BufferedReader in = new BufferedReader(new InputStreamReader(is,"utf-8"));
     StringBuffer buffer = new StringBuffer();
     String line = "";
     while ((line = in.readLine()) != null){
       buffer.append(line).append("\n");
     }
     return buffer.toString();
  }
}


 

 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值