【问题标题】:Posting to a webservice using httpurlconnection使用 httpurlconnection 发布到 web 服务
【发布时间】:2014-08-04 20:01:00
【问题描述】:

为什么我只能在 .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();
        }
    }

}

【问题讨论】:

  • .asmx 不是顶级域。
  • @GriffeyDog 我需要做什么才能发布到 .asmx 网址,或将一串数据发送到 .asmx 网址?有什么技巧可以使用或继续做吗?
  • 您需要知道正确的 URL 才能访问您尝试访问的任何 Web 服务。我所知道的是它不会采用您的示例显示的形式。

标签: java eclipse web-services asmx httpurlconnection


【解决方案1】:

使用“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 标头。

【讨论】:

    猜你喜欢
    • 2016-10-26
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 2015-07-28
    • 2016-12-28
    • 1970-01-01
    • 2011-03-07
    • 2011-01-19
    相关资源
    最近更新 更多