当前位置:首页 > 开发 > 编程语言 > Http > 正文

HTTP 协议通信

发表于: 2012-01-18   作者:周凡杨   来源:转载   浏览:
摘要:                         一:简介  HTTPCLIENT,通过JAVA基于HTTP协议进行点与点间的通信!     二: 代码举例      测试类: import java

 

                     

一:简介

 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. 对得到后的内容进行处理

 

HTTP 协议通信

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
HTTP协议介绍 HTTP协议介绍   Http(Hypertext Transfer Protocol)超文本传输协议。   Http是
WCF中经常会使用HTTP协议与Tcp协议来实现双工通讯,对应使用的协议分别为WsDualHttpBinding、NetTcp
Android之Http通信——1.初识Http协议 引言: 今天是六一儿童节,先在这里给各位超龄儿童说声节日快乐
HTTP协议规定,请求从客户端发出,最后服务器端响应该请求并返回。换句话说,肯定是先从客户端开始
本来从来没有仔细研究过Http协议,今天因为公司业务需求,调试了半天,终于现在会Winform用Http协议
在TCP/IP协议栈中的位置 HTTP协议通常承载于TCP协议之上,有时也承载于TLS或SSL协议层之上,这个时
整个web都离不开http协议,所以了解http协议必不可少,多思考思考Form表单,浏览器,struts,servle
转自http://yzd.iteye.com/blog/1405107 什么是HTTP协议 协议是指计算机通信网络中两台计算机之间进
引言 HTTP协议我想任何IT 人士都耳熟能详了,大家都能说出个所以然来。但是如果我问你HTTP协议的请
HTTP简介 l 客户端连上web服务器后,若想获得web服务器中的某个web资源,需遵守一定的通讯格式,HTT
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号