![](/img/trans.png)
[英]How to send a PUT request with multipart/form-data body with Java Http Client?
[英]How to form protobuf resource part of http request body and test it through dhc client or postman for restful services
我已經創建了一個 .proto 消息,並且公開了一個 rest 服務,它看起來像這樣
@Path("/test")
public interface test{
@POST
@Produces("application/x-protobuf")
@Consumes("application/x-protobuf")
public Response getProperties(TestRequest testrq);
}
現在 TestRequest 是 Java 生成的文件 of.protobuf 我如何在請求正文中傳遞它?
這將是 .proto 文件格式
message TestRequest
{
string id = 1;
string name = 2;
enum TestType
{
Test=1
}
TestType testType = 3;
}
如果您需要一個簡單的 protobuf api 客戶端,請嘗試一下Protoman 。
免責聲明:這是我的副業
您可以使用此代碼片段來測試 protobuf,因為我找不到 postman 或 dhcclient 的任何解決方案
URL url = new URL("https://localhost:8080/test");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setDoInput(true);
urlc.setDoOutput(true);
urlc.setRequestMethod("POST");
urlc.setRequestProperty("Accept", "application/x-protobuf");
urlc.setRequestProperty("Content-Type","application/x-protobuf");
TestRequestPb.TestRequest.Builder testRequestBuilder = TestRequestPb.TestRequest.newBuilder();
TestRequest testRequest = testRequestBuilder.build();
testRequest.writeTo(urlc.getOutputStream());
testRequest = TestRequest.newBuilder().mergeFrom(urlc.getInputStream()).build();
您可以使用命令行工具protoCURL將 Protobuf 有效負載發送到您的 HTTP REST 端點並對其進行調試。 它的工作原理與 cURL 一樣 - 除了您可以使用Protobuf 文本格式或 JSON 格式來描述您的請求,這將被自動編碼和解碼。 由於接受的答案實際上並未使用 postman 或 dhc 客戶端,因此我認為 CLI 可能對您或其他讀者來說是可以接受的。
在您的情況下,請求將如下所示:
protocurl -I path/to/proto -i ..TestRequest -o ..TestResponse \
-u http://localhost:8080/test \
-d "id: 'myid', name: 'myname', testType: Test"
假設 your.proto 文件位於文件夾path/to/proto
中。
但是,因為您的 .proto 文件沒有指定響應類型 TestResponse,所以無法顯示它。 您需要將響應消息添加到您的 .proto 文件。 然而,即使沒有其消息模式,也存在顯示響應的未決問題。
您可以在存儲庫中找到輸出示例。
免責聲明:我是這個的創造者並做到了,因為我遇到了同樣的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.