如何使用http-client在API中发送实体

发布于 2025-02-01 03:00:44 字数 5133 浏览 2 评论 0 原文

我必须在客户端的一个API中调用删除方法。 这不是一个问题,但我正在为公司当前使用的框架而苦苦挣扎,希望我能获得一些希望可以帮助我解决问题的信息:

首先。

1:如果我打电话将params作为URL发送:API不起作用:

2:如果我以X-WWW-Form-urlencedeed发送但不形式或RAW,则可以完全可以使用

API内部方法的文档告诉我们:(重要的是要查看IDETAPA)

“在此处输入图像说明”

我必须在Java中进行此呼叫(Java 8) 目前,我的公司使用http_client作为Apicalls的主要框架。

我的代码: 数据的构建(当前我同时构建作为实体和参数供您查看我尝试过的每一个):

map datosapi = new hashmap<>(); datosapi.put(startants.url,anular_cita);

    Map headers = new HashMap<>();
    headers.put(Constants.AUTHORIZATION, params.get("token_autorizacion"));
    headers.put("Content-Type", "application/json");
    headers.put("entity_charset", "UTF-8");

    datosApi.put(Constants.HEADERS, headers);
    JSONObject entity = new JSONObject();
    Map param = new HashMap();
    param.put(Constants.ID_CENTRO, consul);
    param.put("IdAsistencia", propiedades[0]);
    param.put("IdCapitulo", propiedades[1]);
    param.put("IdEtapa", Integer.valueOf(propiedades[2]));
    entity.put(Constants.ID_CENTRO, consul);
    entity.put("IdAsistencia", propiedades[0]);
    entity.put("IdCapitulo", propiedades[1]);
    entity.put("IdEtapa", Integer.valueOf(propiedades[2]));
    datosApi.put("entity", entity.toString());
    datosApi.put("entity_mime_type", "application/json");
    datosApi.put("entity_charset", "UTF-8");

    datosApi.put("params", param);
    String anularCita = APIDao.callAPIDelete(datosApi);

我的呼叫框架的准备工作:

         public static String callAPIDelete(Map in) {
            String contentString = "";
            Map res = new HashMap<>();
            try {
                res = XWM.execute("delete@http_client", in);
                byte[] content = (byte[]) res.get("content");
                contentString = new String(content, StandardCharsets.UTF_8);
        
   
 

在我们的框架内,我们有:

if (StringUtils.equals(StringUtils.trim(method), "delete"))
                        {
                            StringBuilder requestUrl = new StringBuilder(url);
                            if (formparams != null)
                            {
                                if (requestUrl.indexOf("?")==-1)    requestUrl.append("?");
                                else                                requestUrl.append("&");
                                requestUrl.append(URLEncodedUtils.format(formparams, charset));
                        }
                        
                        if (entityRequest != null)
                        {
                            log.error("Param 'entity' no puede usarse en get (se ignora)");
                        }

                        HttpDelete delete = new HttpDelete(requestUrl.toString());  
                        delete.setConfig(requestConfig);            
                        uriRequest = delete;   
                    }
                }
            }
        }
        
        // Headers
        if (headers != null)
        {
            for (String h: headers.keySet()) uriRequest.addHeader(h, headers.get(h));
        }
        
        // Ejecutamos método
        log.info("Executing request " + uriRequest.getRequestLine());
        CloseableHttpResponse response = null;
        
        if (!preemtiveAuth || credsProvider == null)
        {
            response = httpclient.execute(uriRequest);
        }

如您所见,在删除方法中,我们忽略了我在第一个代码补丁中构建的实体。 HTTPDELETE类是Apache,带有类信息的URL如下:

​:我们可以在删除呼叫中发送实体吗?我在以下位置找到了一些有关此信息的信息:

http删除请求的实体机构是否允许?

https://web.archive.org/web/20090213142728/http://msdn.microsoft.com:80/en-us/library/cc716657.aspx< /a>

https://peterdaugaardrasmussen.com/2020/11/14/rest-should-should-you-use-use-a-body-for-your-your-your-http-delete-requests/

我假设这样做是为了做到这一点,我需要一个新的httpdelete,它可以让我们使用实体,如果可能的话,您可以给我一些例子吗?

2:对于我对上面发布的链接的理解,在不禁止使用实体的同时,如果我只是与制作API的人交谈并要求他们更改配置以允许我们允许我们通过参数发送信息? (这不是个人或明智的信息,只有一堆ID)

非常感谢您的关注,我对任何错别字或格式错误表示歉意,仍然学习如何制作好的帖子。

编辑:我找到了这个答案 httpdelete中的setEntity 或更少的时间,它或更少地解决了第一个问题,即可以在删除电话中发送实体,但现在不应该要求他们更改方法

I have to call a DELETE Method inside one of the APIS of a client.
This shouldn´t be a problem but I am struggling with the framework that my company currently uses and I hope I can get some info that hopefully will help me solve the problem:

First thing first.

1: The api doesn´t work if I do the call sending the params as URL:
enter image description here

2: It works completely OK if I send the params inside the body as x-www-form-urlencoded but not form-data or raw
enter image description here

The documentation of the method inside the API told us the following: (Important to Look to IDEtapa)

enter image description here

I have to do this call in JAVA (JAVA 8)
currently my company uses HTTP_CLIENT as the main framework for APICalls.

My code:
The build of the Data (Currently I build both, as Entity and as Params for you to view I´ve tried with each one of them indepently):

Map datosApi = new HashMap<>();
datosApi.put(Constants.URL, anular_cita);

    Map headers = new HashMap<>();
    headers.put(Constants.AUTHORIZATION, params.get("token_autorizacion"));
    headers.put("Content-Type", "application/json");
    headers.put("entity_charset", "UTF-8");

    datosApi.put(Constants.HEADERS, headers);
    JSONObject entity = new JSONObject();
    Map param = new HashMap();
    param.put(Constants.ID_CENTRO, consul);
    param.put("IdAsistencia", propiedades[0]);
    param.put("IdCapitulo", propiedades[1]);
    param.put("IdEtapa", Integer.valueOf(propiedades[2]));
    entity.put(Constants.ID_CENTRO, consul);
    entity.put("IdAsistencia", propiedades[0]);
    entity.put("IdCapitulo", propiedades[1]);
    entity.put("IdEtapa", Integer.valueOf(propiedades[2]));
    datosApi.put("entity", entity.toString());
    datosApi.put("entity_mime_type", "application/json");
    datosApi.put("entity_charset", "UTF-8");

    datosApi.put("params", param);
    String anularCita = APIDao.callAPIDelete(datosApi);

The preparation for my call to the framework:

         public static String callAPIDelete(Map in) {
            String contentString = "";
            Map res = new HashMap<>();
            try {
                res = XWM.execute("delete@http_client", in);
                byte[] content = (byte[]) res.get("content");
                contentString = new String(content, StandardCharsets.UTF_8);
        
   
 

And inside our framework we have this:

if (StringUtils.equals(StringUtils.trim(method), "delete"))
                        {
                            StringBuilder requestUrl = new StringBuilder(url);
                            if (formparams != null)
                            {
                                if (requestUrl.indexOf("?")==-1)    requestUrl.append("?");
                                else                                requestUrl.append("&");
                                requestUrl.append(URLEncodedUtils.format(formparams, charset));
                        }
                        
                        if (entityRequest != null)
                        {
                            log.error("Param 'entity' no puede usarse en get (se ignora)");
                        }

                        HttpDelete delete = new HttpDelete(requestUrl.toString());  
                        delete.setConfig(requestConfig);            
                        uriRequest = delete;   
                    }
                }
            }
        }
        
        // Headers
        if (headers != null)
        {
            for (String h: headers.keySet()) uriRequest.addHeader(h, headers.get(h));
        }
        
        // Ejecutamos método
        log.info("Executing request " + uriRequest.getRequestLine());
        CloseableHttpResponse response = null;
        
        if (!preemtiveAuth || credsProvider == null)
        {
            response = httpclient.execute(uriRequest);
        }

As you can see, in the delete method, we ignore the entity that i´ve built in the first patch of code.
The HTTPDelete Class is APACHE, the url with info of the class is the following:
https://www.javadoc.io/doc/org.apache.httpcomponents/httpclient/4.5.2/org/apache/http/client/methods/HttpDelete.html

The question can be divided in two:

1: Can we send the Entity in a Delete Call? I have found a few info about this in the following places:

Is an entity body allowed for an HTTP DELETE request?

https://web.archive.org/web/20090213142728/http://msdn.microsoft.com:80/en-us/library/cc716657.aspx

https://peterdaugaardrasmussen.com/2020/11/14/rest-should-you-use-a-body-for-your-http-delete-requests/

I assume that in order to do it, i would need a new HttpDelete that would allow us to use entity, if possible, could you give me some examples of this?

2: For what i understand of the links i posted above, while using entity in Delete calls is not forbidden is something that is not encouraged, Should I just talk with the people who made the API and ask them to change their configuration to allow us to send the info by params? (It is not personal or sensible info, just a bunch of IDs)

Thank you so much for your attention and my apologies for any typo or format mistake, still learning how to make good posts.

EDIT: i have found this answer setEntity in HttpDelete that more or less solve the first issue about if its, posible to send an Entity in a Delete call, but still, don´t now if it should be better to ask them to change their method

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的他你的她 2025-02-08 03:00:44

正如Ewramner和VoiceOfunReason的Coments所说的那样:

1:关于如何做到这一点的答案是在Stackoverflow的较旧帖子中找到的: httpdelete中的设定

2:关于“我应该只是与制作API的人交谈并要求他们更改其配置以允许我们通过参数发送信息?”他们俩都回答了。虽然不禁止,但这是不建议的。

我的行动将是:

1:与负责API的人交谈,以提供有关这种情况的信息。

2:要求我们的架构团队创建一种新方法,该方法将使我们能够与实体机构进行HTTPDELETE调用,以防万一我们必须进行更多这样的API呼叫。

有了这个,我认为我所有的答案都得到了解决。

再一次,谢谢。

As told in the coments by Ewramner and VoiceOfUnreason and in the edits:

1: The answer about how to make this was found in an older post of StackOverflow: setEntity in HttpDelete

2: The answer about "Should I just talk with the people who made the API and ask them to change their configuration to allow us to send the info by params?" was answered by both of them. While it´s not forbidden, it´s something thats not recommended.

My course of action will be:

1: Talk with the people responsible for the API to give them info about this situation.

2: Ask our Architecture team to create a new method that will allow us to do HttpDelete calls with an entity body, just in case that we have to make more API calls like this one.

With this i think all my answers are solved.

Again, Thank you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文