gpt4 book ai didi

java - Android:将 xml 作为文档对象发送,POST 方法

转载 作者:行者123 更新时间:2023-12-01 15:58:25 24 4
gpt4 key购买 nike

我是编程新手,需要一些帮助=/

网络服务已经写好了,但不是我写的。所以我所要做的就是通过 Web 服务通过 post 方法将 xml 作为文档对象发送。

我的代码:

public class send extends application {

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://app.local/test/");

try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("packet");
rootElement.setAttribute("version", "1.2");
document.appendChild(rootElement);

Element em = document.createElement("imei");
em.appendChild(document.createTextNode("000000000000000"));
rootElement.appendChild(em);

em = document.createElement("username");
em.appendChild(document.createTextNode("5555"));
rootElement.appendChild(em);

HttpResponse response = httpclient.execute(httppost);

} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}

}

最佳答案

我对 Android 编程也很陌生。但是,我使用以下方式解决了这些问题。

public void send(){

DefaultHttpClient httpClient = new DefaultHttpClient();

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Servername", "abc"));
nameValuePairs.add(new BasicNameValuePair("UserName", "123));
nameValuePairs.add(new BasicNameValuePair("PassWord", "123"));
nameValuePairs.add(new BasicNameValuePair("XML", getRequestTypeStringBuilder()));

// Your every parameter name must be match with passing parameter, otherwise it throw
// an exception if it in case sensitive

HttpPost httpPost = new HttpPost("http://app.local/DeviceLogin/");
httpPost.addHeader("Accept", "text/xml");
httpPost.setHeader("Content-Type","application/xml;charset=UTF-8");
httpPost.setEntity(nameValuePairs);

HttpResponse response = httpClient.execute(httpPost);

// Be aware, if your return data type is also xml, then using replace empty string,
// otherwise, it my not retrieve or seen all data.

}

private static String getRequestTypeStringBuilder(){
StringBuilder body = new StringBuilder("<?xml version=\"1.0 \"encoding=\"UTF-8\"?>");
body.append("<!DOCTYPE My System\"Abc.dtd\">");
// Please append detail your xml body in here;
return body.toString();
}

希望这可以解决您的问题

“愿一切众生幸福”

问候和慈悲,林布一郎郎

关于java - Android:将 xml 作为文档对象发送,POST 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4544574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com