您的位置:首页 > 其它

post 方式提交XML文件调用接口

2012-07-19 10:31 295 查看
import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpStatus;

import org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.httpclient.methods.RequestEntity;

import org.apache.commons.httpclient.methods.StringRequestEntity;

  

public class Test {

 /**

  * @param args

  */

 public static void main(String[] args) throws Exception{

 

//直接字符串拼接

  StringBuffer sb = new StringBuffer();

  sb.append("<app_ei_sync_req><enabler_id>pengxwtest</enabler_id><dev_id>pengxwtest</dev_id>" +

    "<app_id>pengxwtest</app_id><app_secret>pengxwtest</app_secret>" +

    "<app_status>2</app_status><app_level>0</app_level><app_ei><ei_id>1</ei_id>" +

    "<ei_id>2</ei_id><ei_id>3</ei_id></app_ei></app_ei_sync_req>");//xml数据存储

  String data = sb.toString();

  String url = "接口地址";

  HttpClient httpclient = new HttpClient();

        PostMethod post  = new PostMethod(url);

        String info = null;

        try { 

            RequestEntity entity = new StringRequestEntity(data, "text/xml", 

            "iso-8859-1"); 

            post.setRequestEntity(entity); 

            httpclient.executeMethod(post);

            int code = post.getStatusCode(); 

            if (code == HttpStatus.SC_OK) 

                info = new String(post.getResponseBodyAsString());  //接口返回的信息

        } catch (Exception ex) { 

            ex.printStackTrace(); 

        } finally { 

            post.releaseConnection(); 

        } 

  System.out.println(info);

  

 }

 

//读取xml文件

public class xmlTool(){

InputStreamReader read = new InputStreamReader (new FileInputStream("f://aa.xml"),"UTF-8");

  StringBuffer sb = new StringBuffer();

 

     BufferedReader br = new BufferedReader(read);

     String row;

     while((row = br.readLine())!=null){

      sb.append(row.trim());

     }

     String data = sb.toString();

     String url = "http://localhost:9099/vtoss/cloudapi/rp_video_transcode_batch.do";

   HttpClient httpclient = new HttpClient();

         PostMethod post  = new PostMethod(url);

         String info = null;

         try { 

             RequestEntity entity = new StringRequestEntity(data, "text/xml", 

             "UTF-8"); 

             post.setRequestEntity(entity); 

             httpclient.executeMethod(post);

             int code = post.getStatusCode(); 

             if (code == HttpStatus.SC_OK) 

                 info = new String(post.getResponseBodyAsString()); 

         } catch (Exception ex) { 

             ex.printStackTrace(); 

         } finally { 

             post.releaseConnection(); 

         } 

         System.out.println(info);

 

 

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息