为什么我只被允许向 .com 网址发帖,而不能向 .asmx 网址发帖?我有点困惑,因为我通常想做的是将 xml 内容最终发送到 .asmx url Web 服务。任何人都可以向我提供提示,说明为什么这不起作用,以及如何发布到 .asmx 文件?
public class POSTSenderExample {
public String echoCuties(String query) throws IOException {
// Encode the query
String encodedQuery = URLEncoder.encode(query, "UTF-8");
// This is the data that is going to be send to itcuties.com via POST request
// 'e' parameter contains data to echo
String postData = "e=" + encodedQuery;
URL url = new URL("http://echo.itgeeeks.asmx");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(postData.length()));
// Write data
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
// Read response
StringBuilder responseSB = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ( (line = br.readLine()) != null)
responseSB.append(line);
// Close streams
br.close();
os.close();
return responseSB.toString();
}
// Run this example
public static void main(String[] args) {
try {
System.out.println(new POSTSenderExample().echoCuties("Hi there!"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
最佳答案
使用“POST”是正确的。
而不是打电话 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 你必须打电话 connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); (如果您使用 utf-8 编码,则可能是这种情况)。
您还必须在 http- header 中设置 SOAP 操作: 连接.setRequestProperty("SOAPAction", SOAPAction); 您可以在 wsdl- 文件中找到 SOAP 操作。我做了什么来找出所有预期的参数:我使用了一个工作的 WS 客户端,并跟踪 TCP 流量以找出预期的 HTTP header 。
关于java - 使用 httpurlconnection 发布到 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25126593/