java中有没有办法使用PostMethod或HttpPost以及url参数发布XML?我正在做类似下面的事情,但它没有用。
URL - https://mytest.com?z=123&b=abc&c=%10
xml - <test>
<data> This is test XML </data>
</test>
public String getResponse(String xml) {
HttpClient client = new HttpClient();
// "https://mytest.com?z=123&b=abc&c=%10"
String url="https://mytest.com";
PostMethod pMethod = new pMethod(url);
pMethod.addParameter("z","123");
pMethod.addParameter("b","abc");
pMethod.addParameter("c","%10");
post.setRequestEntity(new StringRequestEntity(xml, "application/xml", "UTF-8"));
client.executeMethod(pMethod);
}
答案 0 :(得分:1)
我想我第一次误解了你的问题。您希望将XML作为URL参数传递,但是通过POST而不是直接在URL中包含XML?你可以这样做:
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
public class XMLPoster {
public static void main(String[] argv) {
try {
String XMLData = argv[0];
URL url = new URL("http://posttestserver.com/post.php");
String myParam = "myparam=" + URLEncoder.encode(XMLData, "UTF-8");
HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Length", Integer.toString(myParam.length()));
httpConn.setDoOutput(true);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter((httpConn.getOutputStream())));
writer.write(myParam, 0, myParam.length());
writer.flush();
writer.close();
System.out.println(httpConn.getResponseCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
然后如果你运行:
$ java -cp . XMLPoster '<ThisXMLisFake>But how do you know?</ThisXMLisFake>'
200
并在posttestserver.com上找到相应的文件,它应该包含这个,希望你想要的是:
Post Params:
key: 'myparam' value: '<ThisXMLisFake>But how do you know?</ThisXMLisFake>'
Empty post body.
Upload contains PUT data:
myparam=%3CThisXMLisFake%3EBut+how+do+you+know%3F%3C%2FThisXMLisFake%3E
答案 1 :(得分:0)
你可以使用内置的Java这样的东西:
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
public class XMLPoster {
public static void main(String[] argv) {
try {
String XMLData = argv[0];
URL url = new URL("http://posttestserver.com/post.php");
HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
httpConn.setRequestProperty("Content-Length", Integer.toString(XMLData.length()));
httpConn.setDoOutput(true);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter((httpConn.getOutputStream())));
writer.write(XMLData, 0, XMLData.length());
writer.flush();
writer.close();
System.out.println(httpConn.getResponseCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
此代码当然只是一个示例,不会进行错误检查等。