Java的REST API使用HTTP PUT方法发送数组

huangapple go评论66阅读模式
英文:

Java REST api Send array using HTTP PUT method

问题

以下是您要求的翻译内容:


我无法在Java中实现一个REST API。

我有一个使用PHP的通用实现的工作示例。

我如何使用json库和HttpClient(HttpPut请求)在Java中实现它?

以下是PHP示例代码:

//要更新的数据
$postData = array(
    'item'   => array(
        'title'              => 'My title',
        'personal_reference' => 'My personal ref',
        'qty'                => 3,
        'description'        => 'My description'
    )
);

//使用PUT方法的资源调用
$url = 'https://rest.restserv.com/item/1234?token=MyPersonalToken';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$xml_response  = curl_exec($ch);

我(不起作用的)尝试如下:

Map<String, String> dataMap = new HashMap<String, String>();
dataMap.put("title", "some text");
dataMap.put("personal_reference", "my ref");
dataMap.put("qty", "1");
dataMap.put("description", "some desciption text");

String url = "https://rest.restserv.com/item/1234?token=MyPersonalToken";

HttpPut putRequest = new HttpPut(url);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (Map.Entry<String, String> entry : dataMap.entrySet()) {
    builder.addTextBody(entry.getKey(), entry.getValue());
}
putRequest.setEntity(builder.build());
response = httpClient.execute(putRequest);

感谢并致以最诚挚的问候。

更新

现在我正在尝试另一种方法。对象Map<String, String> dataMap 包含要发送的项目的所有细节。不幸的是,我仍然无法发送项目细节。请求状态为200,响应也是正常的。

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPut putRequest = new HttpPut(url);
putRequest.addHeader("Content-Type", "application/json; charset=utf-8");
JSONArray itemDetails = new JSONArray();
itemDetails.put(dataMap);
JSONObject root = new JSONObject().put("item", itemDetails);
StringEntity entity = new StringEntity(root.toString(2), "UTF-8");
System.out.println("ROOT is:::: " + root.toString(2));
putRequest.setEntity(entity);
response = httpClient.execute(putRequest);

root.toString(2) 的结果是:

{
  "item": [
    {
      "title": "My title",
      "personal_reference": "My personal ref",
      "qty": "3",
      "description": "My description"
    }
  ]
}

英文:

I'm not able to implement an REST API in Java

I've got a working example of a generic implementation using PHP.

How I can implement it in Java using json library and HttpClient (HttpPut request) ?

Here it is the PHP example

//DATA TO UPDATE
$postData = array(
    &#39;item&#39;   =&gt; array(
        &#39;title&#39;              =&gt; &#39;My title&#39;,
        &#39;personal_reference&#39; =&gt; &#39;My personal ref&#39;,
        &#39;qty&#39;                =&gt; 3,
        &#39;description&#39;        =&gt; &#39;My description&#39;
    )
);


//RESOURCE CALL WITH PUT METHOD
$url = &#39;https://rest.restserv.com/item/1234?token=MyPersonalToken&#39;;
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POSTFIELDS, http_build_query($postData) );
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, &quot;PUT&quot;);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$xml_response  = curl_exec($ch);

My (not working) approach was this:

Map&lt;String,String&gt; dataMap = new HashMap&lt;String,String&gt;();
dataMap.put(&quot;title&quot;, &quot;some text&quot;);
dataMap.put(&quot;personal_reference&quot;, &quot;my ref&quot;);
dataMap.put(&quot;qty&quot;, &quot;1&quot;);
dataMap.put(&quot;description&quot;, &quot;some desciption text&quot;);

String url = &quot;https://rest.restserv.com/item/1234?token=MyPersonalToken&quot;;

HttpPut putRequest = new HttpPut(url);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (Map.Entry&lt;String, String&gt; entry : dataMap.entrySet()) {
	builder.addTextBody(entry.getKey(), entry.getValue());
}
putRequest.setEntity(builder.build());
response = httpClient.execute(putRequest);

thanks and best regards.

UPDATE

Now I'm trying with this other approach. The object Map<String,String> dataMap contains all the details of the item to send. Unfortunately i'm still not able to send item details. The request status is 200 and also the response is ok.

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPut putRequest = new HttpPut(url);
putRequest.addHeader(&quot;Content-Type&quot;, &quot;application/json; charset=utf-8&quot;);
JSONArray itemDetails = new JSONArray();				
itemDetails.put(dataMap);				
JSONObject root = new JSONObject().put(&quot;item&quot;, itemDetails);
StringEntity entity = new StringEntity(root.toString(2),  &quot;UTF-8&quot;);
System.out.println(&quot;ROOT is:::: &quot;+root.toString(2));
putRequest.setEntity(entity);
response = httpClient.execute(putRequest);

root.toString(2) result is:

> {"item": [{"title": "My title","personal_reference": "My personal
> ref","qty": "3","description": "My description"}]}

答案1

得分: 0

问题

似乎负载的格式不正确,导致 REST 服务器跳过了它们。

解决方法

通过使用 kong.unirest.Unirest 库解决了这个问题。

再见

英文:

PROBLEM

It seems that payload wasn't correctly formatted and were skipped by the REST server.

SOLUTION

The problem has been solved using kong.unirest.Unirest library.

Bye

huangapple
  • 本文由 发表于 2020年10月1日 22:42:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64157730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定