Android,通过HTTP将XML字符串发送到服务器

时间:2011-07-19 13:05:07

标签: java android xml http post

我最近开始做Android编程。我遇到了一个问题。目前我已经构建了一个名为'sendData'的XML字符串请求。需要将此sendData发送到服务器以验证用户帐户是否有效。

目前,当我尝试发送请求时,我与服务器进行了联系,但是我收到了一个默认的通用响应错误,这让我相信XML没有得到正确的发送。

public void postData(String sendData) {
        // Create a new HttpClient and Post Header
        System.out.println("SENDDATA" + sendData);
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www......");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(0);
            nameValuePairs.add(new BasicNameValuePair(sendData, sendData));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            inputStreamToString(response.getEntity().getContent());

        } 
        catch (ClientProtocolException e) 
        {
            // TODO Auto-generated catch block
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
        }
    } 

以上是我用来发送数据的代码。我相信这个问题可能发生在'try'部分。我在这个论坛上搜索过类似的问题,找不到我想要的答案。

任何帮助将不胜感激。

谢谢,

编辑:

在日志中。当我打开字符串时,它看起来像这样。

07-19 15:35:36.642: INFO/System.out(2204): <Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="1.0" xsi:noNamespaceSchemaLocation="http://www.example.com">
07-19 15:35:36.642: INFO/System.out(2204): <Identification>
07-19 15:35:36.642: INFO/System.out(2204): <UserID>username@example.com</UserID>
07-19 15:35:36.642: INFO/System.out(2204): <Password>password</Password>
07-19 15:35:36.642: INFO/System.out(2204): </Identification>
07-19 15:35:36.642: INFO/System.out(2204): <Service>
07-19 15:35:36.652: INFO/System.out(2204): <ServiceName>AccountVerify</ServiceName>
07-19 15:35:36.652: INFO/System.out(2204): <ServiceDetail/>
07-19 15:35:36.652: INFO/System.out(2204): </Service>

07-19 15:35:36.652:INFO / System.out(2204):

每个元素在LogCat中都有自己的行。这可能是问题吗?

2 个答案:

答案 0 :(得分:2)

我得到了答案。问题是,在进一步查看时,实际请求中没有发送任何信息。解决方案是删除阵列并通过设置新实体来替换它。更改/工作代码如下:

        try {
            StringEntity se = new StringEntity(sendData);
            httppost.setEntity(se);
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            System.out.println("Message Sent!");
            inputStreamToString(response.getEntity().getContent());
            } 

答案 1 :(得分:0)

我强烈建议您使用Fiddler Web Debugger来帮助您检测要发送的内容。这是一个很棒的工具,可以节省很多时间。

您发布的代码存在一些错误问题。

您正在创建的arraylist的大小为0,设置为1会更有效(因为您只添加一个NameValuePair

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

第一个BasicNameValuePair构造函数参数错误,应该是某种键名

nameValuePairs.add(new BasicNameValuePair("mySendData", sendData));