【问题标题】:Android, send and receive XML via HTTP POST methodAndroid,通过 HTTP POST 方法发送和接收 XML
【发布时间】:2015-05-07 14:05:55
【问题描述】:

有一个相关的问题,但我无法清楚地得到答案。

我想发布一个简短的 xml 代码

<aaaLogin inName="admin" inPassword="admin123"/>

通过 HTTP 发送到特定的 URL 地址。 Web 服务将返回给我一个 XML 代码。重要的部分是我将解析收到的 XML,并将其存储为文件。

    // Create a new HttpClient and Post Header  
    HttpClient httpclient = new DefaultHttpClient();  
    HttpPost httppost = new HttpPost("http://192.168.192.131/"); //URL address

    StringEntity se = new StringEntity("<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>",HTTP.UTF_8); //XML as a string
    se.setContentType("text/xml"); //declare it as XML
    httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
    httppost.setEntity(se);

    BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient .execute(httppost);
    tvData.setText(httpResponse.getStatusLine().toString()); //text view is expected to print the response

接收响应有问题。此外,我没有写任何东西来将接收到的 XML 保存为文件。有人能写个代码sn-p吗?

【问题讨论】:

    标签: android xml http http-post


    【解决方案1】:

    好的,我在发布这个问题后不久就想通了。 这段代码在这里工作正常:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://192.168.192.131/");
    
    try {
        StringEntity se = new StringEntity( "<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>", HTTP.UTF_8);
        se.setContentType("text/xml");
        httppost.setEntity(se);
    
        HttpResponse httpresponse = httpclient.execute(httppost);
        HttpEntity resEntity = httpresponse.getEntity();
        tvData.setText(EntityUtils.toString(resEntity));        
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用以下方式获取响应的内容:

      String responseXml = EntityUtils.toString(httpResponse.getEntity());
      

      然后您可以使用 like this 将其写入文件。

      接收响应有问题

      由于您没有说什么收到回复有问题,因此在这一点上帮助您有点困难。

      【讨论】:

        【解决方案3】:

        为什么不在Spring for Android 中使用Spring RestTemplate

        【讨论】:

          猜你喜欢
          • 2013-03-12
          • 2011-02-03
          • 2011-02-18
          • 2014-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多