首页 > 解决方案 > 如何在 java 中发送 SOAP API 调用并以 json 格式返回

问题描述

我正在尝试发送一个 api 调用,然后读取返回的 json 并在返回的 json 信息中打印一个值。卷曲看起来像这样:

curl "https://(address goes here)?where=eq(open,true)&fields=name,totals" \ 
-H 'Api-Key: (api key here)'

这是我到目前为止所拥有的:

import java.io.*;
import java.net.*;
import org.json.JSONObject;
import java.util.LinkedHashMap;
import java.util.Map;

public class Caller {

public void APICall(String str) throws Exception
{
    String url = "(address)" + str + 
    "(address continued)";

    URL obj = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

    conn.setRequestProperty("Api-Key",  
    "(API Key)";
    conn.setDoOutput(true);
    conn.setDoInput(true);

    conn.setRequestMethod("PUT");
    JSONObject data = new JSONObject();

    OutputStreamWriter out = new 
    OutputStreamWriter(conn.getOutputStream());
    out.write(data);

    BufferedReader in = new BufferedReader(
          new InputStreamReader(conn.getInputStream()));

    String inputLine;

     StringBuffer response = new StringBuffer();
     while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
     }
    in.close();
    out.close();



}

}

然后我从另一个这样的类中调用它:

           try {
           call.APICall(codeArray.get(x));
            } catch (Exception e) {
             e.printStackTrace();
           }

str 是该地址输入的 API 代码,codeArray.get(x) 是存储的 API 代码。我不确定如何在 curl 代码中添加参数或以 json 格式返回。我已经隐藏了地址和 API 密钥。

标签: javajsonapipostsoap

解决方案


我认为您需要更多地解释您发送的 SOAP 有效负载和收到的答案,以及您希望返回的 JSON 是怎样的,但我会猜测您要问什么并尝试回答它。

我可以在代码中看到您将 JSON 发送到 API 调用,因此我假设客户端将使用 SOAP 使用您的端点。您调用的 API 应该返回 JSON 对吗?您的端点将返回一个 SOAP XML 答案(或者它应该是原始 JSON?),因此您必须进行从 JSON 到 XML (SOAP) 的转换。

如果您想向客户端返回 JSON 并发送 SOAP XML 有效负载,请阅读以下段落。

如果您在服务器端或客户端使用框架,您可能希望返回一个 XML,返回一个 JSON,如果您在服务器端或客户端使用框架,则必须阅读文档。如果可以通过框架更改标头(服务器端),您应该接受 XML 格式 ( Accept: application/soap+xml; charset=utf-8) 并发送到您的客户端Content-type: application/json。在您的客户端中,当您发送请求时,您必须具有 和 的标Content-type: application/soap+xml; charset=utf-8Accept: application/json

TL;博士; (用于客户端发送 XML 和接收 JSON)

服务器:

Accept: application/soap+xml; charset=utf-8
Content-type: application/json

客户:

Accept: application/json
Content-type: application/soap+xml; charset=utf-8

资源:

标题字段定义

SOAP 标头 HTTP


推荐阅读