如何在HTTP中发布XML

时间:2012-04-17 16:24:36

标签: android

我需要通过http发送一个xml内容。我已经尝试了一些方法,但它没有用。参数应如下所示{“action”=>“login”,“controller”=>“session”,“user”=> {“username”=>“123@gmail.com”,“密码“=>”[FILTERED]“}}而该操作和控制器参数是在用户标记内的服务器(即)中预定义的,用户名和密码都应该来......

XML代码块将是

             <?xml version=\"1.0\" encoding=\"UTF-8\"?>
             <user>
             <username>xxx</username>
             <password>yyyy</password>
             </user>

我的代码是

String param1 = null;
param1 = URLEncoder.encode(charset);

String param2 = null;
try {
    param2 = URLEncoder.encode("x@yyy.com", charset);
} catch (UnsupportedEncodingException e3) {
    // TODO Auto-generated catch block
    e3.printStackTrace();
} 
String param3 = null;
try {
    param2 = URLEncoder.encode("xxx", charset);
} catch (UnsupportedEncodingException e4) {
    // TODO Auto-generated catch block
    e4.printStackTrace();
}

String query = String.format("user=&username=%s&password=%s", param1, param2,param3);*/

URLConnection urlConnection = null;
try {
    urlConnection = new URL(url).openConnection();
} catch (MalformedURLException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
} catch (IOException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
}
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true); // Triggers POST.
//urlConnection.setRequestProperty("accept-charset", charset);
urlConnection.setRequestProperty("content-type", "application/xml");

OutputStreamWriter writer = null;
try {
    writer = new OutputStreamWriter(urlConnection.getOutputStream());
    writer.write(query); // Write POST query string (if any needed).
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    if (writer != null) try { writer.close(); } catch (IOException logOrIgnore) {}
}

try {
    InputStream result = urlConnection.getInputStream();
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

0 个答案:

没有答案