2012-10-01 57 views
1

我有一个我想用来获取数据的API。为了获取数据,我必须以XML格式发送请求,并且将以XML格式发送响应。有没有人有任何示例如何使用Java发送请求以及如何解码Java中的响应。Java中的XML请求/响应

+1

你的意思是SOAP吗? – elias

+1

你的问题对我来说太模糊...... 你在说网络服务吗?什么API基于?也许它只是一个http连接到soe servlet?请详细说明一下 –

+1

您是否可以更具体地了解您希望如何通过XML发送请求?它可以通过POST,SOAP,AIM SIM等来完成...以及什么 - web服务,网页..签出javax.xml.soap包 –

回答

2

嗯,我有你想要的...现在,但我想请您使用以下API ...

  • JAXPJAXB
  • Castor

-的下面的代码片段方法接受网络服务器的urlxmlQuery

-我已经使用了NameValuePair发送XML请求

-更换MySSLSocketFactory.getNewHttpClient();Http客户,我都用这个,它需要的自定义证书访问此site.`

这是从我的项目,它可以发送XML REQ和回来的XML RESP代码:

public String postData(String url, String xmlQuery) { 

     final String urlStr = url; 
     final String xmlStr = xmlQuery; 
     final StringBuilder sb = new StringBuilder(); 

     Thread t1 = new Thread(new Runnable() { 

      public void run() { 

       HttpClient httpclient = MySSLSocketFactory.getNewHttpClient(); 

       HttpPost httppost = new HttpPost(urlStr); 

       try { 

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
          1); 
        nameValuePairs.add(new BasicNameValuePair("xml", xmlStr)); 

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

        HttpResponse response = httpclient.execute(httppost); 

        Log.d("Vivek", response.toString()); 

        HttpEntity entity = response.getEntity(); 
        InputStream i = entity.getContent(); 

        Log.d("Vivek", i.toString()); 
        InputStreamReader isr = new InputStreamReader(i); 

        BufferedReader br = new BufferedReader(isr); 

        String s = null; 

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

         Log.d("YumZing", s); 
         sb.append(s); 
        } 

        Log.d("Check Now", sb + ""); 

       } catch (ClientProtocolException e) { 

        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 

     }); 

     t1.start(); 
     try { 
      t1.join(); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     System.out.println("Getting from Post Data Method " + sb.toString()); 

     return sb.toString(); 
    }