2012-10-01 81 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(); 
    }