使用httpurlconnection发布到Web服务

时间:2014-08-04 20:01:00

标签: java eclipse web-services asmx httpurlconnection

为什么我只被允许发布.com网址但不是.asmx网址的帖子?我有点困惑,因为我一般要做的是最终将xml内容发送到.asmx网址服务。任何人都可以向我提供为什么这不起作用的提示,以及我如何发布到.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();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

使用“POST”是正确的。

而不是打电话 connection.setRequestProperty(“Content-Type”,“application / x-www-form-urlencoded”); 你得打电话 connection.setRequestProperty(“Content-Type”,“text / xml; charset = utf-8”); (如果您使用的是utf-8编码,可能就是这种情况)。

您还必须在http-Header中设置SOAP Action: connection.setRequestProperty(“SOAPAction”,SOAPAction); 您可以在wsdl文件中找到SOAP Action eihter。我做了什么来找出所有预期的参数:我使用了一个工作的WS客户端,并跟踪TCP流量以找出预期的HTTP头。