Android-使用HttpURLConnection来发布XML数据 [英] Android - Using HttpURLConnection to POST XML data

查看:172
本文介绍了Android-使用HttpURLConnection来发布XML数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了麻烦,需要一点帮助(请)!

I've run into a bit of a deadend and need a bit of help (please)!

我对Android Dev(以及一般而言的编码)非常陌生.基本上,我需要使用HttpURLConnection将XML数据发布到URL,但无法使其正常工作.我的应用程序已从GET请求读取和粘贴XML数据,但发现POST部分很困难.

I'm very new to Android Dev (and to coding in general). Basically I need to POST XML data to a URL using HttpURLConnection but can't get it to work. I've got my app reading and pasrsing XML data from a GET request but finding the POST part difficult.

我已经研究过创建NameValuePair数组,但是不确定如何使用我需要发布的XML结构来实现此功能.

I've looked at creating a NameValuePair array but not sure how to do this with the XML structure I am needing to post.

XML数据将如下所示:

The XML data will look like this:

<Sheet>
  <Job>jobNumber</Job> 
  <Task>taskNumber</Task> 
  <UserID>3</UserID> 
  <Date>systemDateFormatted</Date> 
  <Minutes>timeToLog</Minutes> 
  <Note>userNote</Note>
</Sheet>

到目前为止,我已经将其用于我的代码.

So far I have this for my code.

try {
        URL url = new URL(theUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);


        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("Sheet", null));
        params.add(new BasicNameValuePair("Job", jobNumber));
        params.add(new BasicNameValuePair("Task", taskNumber));
        params.add(new BasicNameValuePair("UserID", String.valueOf(yourUserID)));
        params.add(new BasicNameValuePair("Date", systemDateFormatted));
        params.add(new BasicNameValuePair("Minutes", timeElapsed));
        params.add(new BasicNameValuePair("UserNote", "Test Note"));
        params.add(new BasicNameValuePair("Sheet", null));

我不确定我是否正确理解NamedValuePair.为我的XML数据创建一个字符串并以这种方式进行POST会更好吗?

I'm not sure if I'm understanding NamedValuePair right. Would it be better to create a string for my XML data and POST this way instead?

谢谢!

推荐答案

是的,POST数据将作为您请求的有效负载.例如

Yes, POST data goes as payload of your request. For example

URL url = new URL(theUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    String body = "<xml...</xml>";
    OutputStream output = new BufferedOutputStream(conn.getOutputStream());
    output.write(body.getBytes());
    output.flush();
finally {
    conn.disconnect();
}

这篇关于Android-使用HttpURLConnection来发布XML数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆