HTTP 协议通信

 

                     

一:简介

 HTTPCLIENT,通过JAVA基于HTTP协议进行点与点间的通信!

 

 

二: 代码举例

 

   测试类:


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.springside.modules.web.struts2.Struts2Utils;
 
import com.asiainfo.boss.inter.boss30.remote.thirdpojo.RecordData;
import com.asiainfo.boss.inter.web.remote.RemoteInvokeFunc;
import com.asiainfo.util.Md5;
import com.asiainfo.util.ParamUtils;
import com.asiainfo.util.URLReader;
import com.asiainfo.web.action.common.FileUtil;
 
public class Test {
    private static final String WTJT_ORDER_NUM = "JTMHZHYY";
    private static final String WTJT_ORDER_NUM_CX = "JTMHZHYYCX";
    private static final String WTJT_KEY = "JTYWTYZXZHYY";    //key=TransactionID+Platform+KEY
    private static final String WTJT_KEY_CX = "JTYWTYZHYYCX";    //key=TransactionID+Platform+KEY
   
    public static void main(String[] args) {
 
         String url = "http://218.206.204.204:8888/jttiyan/order/cxzhyyorder.action";
           long nowTime = System.currentTimeMillis();
           StringBuffer sb = new StringBuffer();
           sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
           sb.append("<GroupOrderCx>");
           sb.append("<TransactionID>");
           sb.append(nowTime);
           sb.append("</TransactionID>");
           sb.append("<Platform>");
           sb.append(WTJT_ORDER_NUM_CX);
           sb.append("</Platform>");
           sb.append("<OrderMsisdn>");
           sb.append("15838346666");
           sb.append("</OrderMsisdn>");
           sb.append("<Key>");
           String key = nowTime+WTJT_ORDER_NUM_CX+WTJT_KEY_CX;//TransactionID+Platform+KEY
           sb.append(Md5.md5s_static(key).toUpperCase());
           sb.append("</Key>");
           sb.append("</GroupOrderCx>");
           String ret;
           try {
              ret = URLReader.getBodyURLContent(url, sb.toString(), "UTF-8");
              System.out.println("ret="+ret);
 
           } catch (Exception e) {
              e.printStackTrace();
           }
       
    }
 
}

 工具类:

package com.asiainfo.util;
 import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
 
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
 
import com.asiainfo.boss.common.util.XmlUtil;
 
public class URLReader {
 
    public static String getURLContent(String url,String queryString,String encoding) throws Exception {
       HttpClient client = new HttpClient();
       // 设置代理服务器地址和端口
       //client.getHostConfiguration().setProxy("192.168.200.254", 3128);
       // 使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https
       HttpMethod method = new GetMethod(url);
       method.setQueryString(queryString);
      
       try {
           int ctimeout = 5000;
           int stimeout = 55000;
           client.getHttpConnectionManager().getParams().setConnectionTimeout(
                  ctimeout);
           client.getHttpConnectionManager().getParams()
                  .setSoTimeout(stimeout);
           client.executeMethod(method);
           // 打印服务器返回的状态
           // System.out.println(method.getStatusLine());
           InputStream l_urlStream = method.getResponseBodyAsStream();
           java.io.BufferedReader l_reader = null;
           String sCurrentLine;
           StringBuilder sTotalString = new StringBuilder();
           l_reader = new java.io.BufferedReader(
                  new java.io.InputStreamReader(l_urlStream, encoding));
           while ((sCurrentLine = l_reader.readLine()) != null) {
              sTotalString = sTotalString.append(new StringBuffer(
                     sCurrentLine));
           }
           sCurrentLine = null;
           l_urlStream.close();
           l_urlStream = null;
           l_reader.close();
           l_reader = null;
 
           method.releaseConnection();
           return sTotalString.toString();
          
       } catch (IOException ex) {
           throw new Exception(ex.getMessage());
       }
    }
   
    public static String getPostURLContent(String url, String queryString, String encoding) throws Exception {
       HttpClient client = new HttpClient();
       // 设置代理服务器地址和端口
       //client.getHostConfiguration().setProxy("192.168.200.254", 3128);
       HttpMethod method = new PostMethod(url);
       method.setQueryString(queryString);
       // 使用POST方法
       // HttpMethod method = new PostMethod("http://java.sun.com");
       try {
           int ctimeout = 5000;
           int stimeout = 55000;
           client.getHttpConnectionManager().getParams().setConnectionTimeout(
                  ctimeout);
           client.getHttpConnectionManager().getParams()
                  .setSoTimeout(stimeout);
           client.executeMethod(method);
           // 打印服务器返回的状态
           // System.out.println(method.getStatusLine());
           InputStream l_urlStream = method.getResponseBodyAsStream();
           java.io.BufferedReader l_reader = null;
           String sCurrentLine;
           StringBuilder sTotalString = new StringBuilder();
           l_reader = new java.io.BufferedReader(
                  new java.io.InputStreamReader(l_urlStream, encoding));
           while ((sCurrentLine = l_reader.readLine()) != null) {
              sTotalString = sTotalString.append(new StringBuffer(
                     sCurrentLine));
           }
           sCurrentLine = null;
           l_urlStream.close();
           l_urlStream = null;
           l_reader.close();
           l_reader = null;
 
           method.releaseConnection();
           return sTotalString.toString();
          
       } catch (IOException ex) {
           throw new Exception(ex.getMessage());
       }
    }
 
    public static String getBodyURLContent(String url,String body,String encoding) throws Exception {
       HttpClient client = new HttpClient();
       // 设置代理服务器地址和端口
       //client.getHostConfiguration().setProxy("192.168.200.254", 3128);
       // 使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https
       PostMethod method = new PostMethod(url);
       //method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
       //method.addRequestHeader("Content-Type","text/html;charset=UTF-8");
       method.setRequestHeader("Content-Type", "text/html;charset="+encoding);
       method.setRequestBody(body);
       try {
           int ctimeout = 5000;
           int stimeout = 55000;
           client.getHttpConnectionManager().getParams().setConnectionTimeout(
                  ctimeout);
           client.getHttpConnectionManager().getParams()
                  .setSoTimeout(stimeout);
           client.executeMethod(method);
           // 打印服务器返回的状态
           // System.out.println(method.getStatusLine());
           InputStream l_urlStream = method.getResponseBodyAsStream();
           java.io.BufferedReader l_reader = null;
           String sCurrentLine;
           StringBuilder sTotalString = new StringBuilder();
           l_reader = new java.io.BufferedReader(
                  new java.io.InputStreamReader(l_urlStream, encoding));
           while ((sCurrentLine = l_reader.readLine()) != null) {
              sTotalString = sTotalString.append(new StringBuffer(
                      sCurrentLine));
           }
           sCurrentLine = null;
           l_urlStream.close();
           l_urlStream = null;
           l_reader.close();
           l_reader = null;
 
           return sTotalString.toString();
          
       } catch (IOException ex) {
           throw ex;
       }finally{
           method.releaseConnection();
       }
    }
   
    /*
     * 下载一个文件到本地,返回true/false
     */
    public static boolean snatchAtFile(String url, String filePath) {
       try {
           HttpClient client = new HttpClient();
           // 设置代理服务器地址和端口
           //client.getHostConfiguration().setProxy("192.168.200.254", 3128);
           int ctimeout = 5000;
           int stimeout = 55000;
           client.getHttpConnectionManager().getParams().setConnectionTimeout(
                  ctimeout);
           client.getHttpConnectionManager().getParams()
                  .setSoTimeout(stimeout);
           GetMethod get = new GetMethod(url);
           client.executeMethod(get);
           File storeFile = new File(filePath);
           FileOutputStream output = new FileOutputStream(storeFile);
           // 得到网络资源的字节数组,并写入文件
           output.write(get.getResponseBody());
           output.close();
           get.releaseConnection();
       } catch (Exception e) {
           return false;
       }
       return true;
    }
 
    
}
 
 
 
 

 

通信结果:

ret的值:
<?xml version="1.0" encoding="UTF-8"?>
<GroupAccOrder>
<TransactionID>1326875539875</TransactionID>
<Platform>JTMHZHYYCX</Platform>
<ResultCode>0000</ResultCode>
<ResultMsg>
<OrderInfo>
<OrderID>1326870197656</OrderID>
<GroupName>公司名称</GroupName>
<OrderTime>2012-01-18 15:03:22</OrderTime>
<OrderSta>1</OrderSta>
<CusManName></CusManName>
<CusMsisdn></CusMsisdn>
</OrderInfo>
<OrderInfo>
<OrderID>1326869919921</OrderID>
<GroupName>公司名称</GroupName>
<OrderTime>2012-01-1814:58:41</OrderTime>
<OrderSta>1</OrderSta>
<CusManName></CusManName>
<CusMsisdn></CusMsisdn>
</OrderInfo>
<OrderInfo>
<OrderID>1326860084421</OrderID>
<GroupName>公司名称</GroupName>
<OrderTime>2012-01-18 12:14:45</OrderTime>
<OrderSta>1</OrderSta>
<CusManName></CusManName>
<CusMsisdn></CusMsisdn>
</OrderInfo>
</ResultMsg>
</GroupAccOrder>
 
 
 

 

总结:

 首先HTTPCLIENT 支持以PostMethodGetMethod 方式进行通信!除了设置PostMethod的实例与GetMethod有些不同之外,剩下的步骤都差不多。

下面来看看它们的实现步骤:

1. 创建 HttpClient 的实例

  2. 创建某种连接方法的实例,在这里是 GetMethod。在 GetMethod 的构造函数中传入待连接的地址

  3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例

  4. response

  5. 释放连接。无论执行方法是否成功,都必须释放连接

  6. 对得到后的内容进行处理

 

你可能感兴趣的:(java,httpclient,http,通信)