1

我正在开发一个 android 项目,在该项目中我需要使用 post 方法将两个 xml 作为参数发送到服务器(即我想以表单形式发送)。我尝试使用以下代码发送数据,但它不起作用。远程数据库中没有数据。

private void postFormData(List<DataItem> ti,String ex,String getExpensesXml)
{    
//Create a new Http Client 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 
try
{ 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("sync","true"));
    nameValuePairs.add(new BasicNameValuePair("tt",ti));
    nameValuePairs.add(new BasicNameValuePair("te",ex)); 

    UrlEncodedFormEntity form; 
    form = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");  
    httppost.setEntity(form); 

    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity entity = response.getEntity();  
    String line = EntityUtils.toString(entity);    
    System.out.println(line);

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

我找不到问题所在。如果有人设法找到问题并建议我解决方案,那就太好了。

我还有两个问题?我在尝试正确的代码吗?有没有其他方法可以通过 Form 将 xml 数据发送到服务器?

提前致谢

4

2 回答 2

0

最后我找到了解决方案,我使用以下代码将数据作为从服务器发送到服务器

URL siteUrl;
    try {
        siteUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) siteUrl
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        String content1 = ""; 

        Set getkey = param.keySet();
        Iterator keyIter = getkey.iterator();
        String content = "";
        for (int i = 0; keyIter.hasNext(); i++) {
            Object key = keyIter.next();
            if (i != 0) {
                content += "&";
            }
            content += key + "=" + param.get(key);
            System.out.println("Content" + content);
        }

        System.out.println(content);
        out.writeBytes(content.trim());
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String line = "";
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
        in.close();


    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    db.close();
}

它可能对像我这样的人有所帮助。

于 2012-08-24T13:41:55.333 回答
0

面临同样的问题。但最终设法将数据发布到服务器。你的代码绝对是它应该的方式,除了你必须编码你的StringtoBase64然后将它传递给NameValuePair. 在服务器端,您必须StringBase64. 它会起作用的。如果你需要,我可以分享代码。

于 2012-12-01T04:40:59.240 回答