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

来源:互联网 发布:网络质量 编辑:程序博客网 时间:2024/05/01 03:05

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);

 

 

}
}

原创粉丝点击