Joh*_*uau 6 java http httprequest
我正在开发一个项目,我请求 api 来发布项目详细信息。以下是我尝试使用 HttpRequest 插入正文 itemstr 的代码
public void test(){
newItem item = new newItem(12,12,12,21,"waiwai");
JSONObject itemobj = new JSONObject(item);
String itemStr = itemobj.toString();
System.out.println(itemStr);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:3001/postMongo")).POST(HttpRequest.BodyPublishers.ofString(itemStr)).build();
}
Run Code Online (Sandbox Code Playgroud)
这是我的 newItem 类
public class newItem {
int id,wholesaleRate,SellingPrice,stock;
String name;
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getWholesaleRate() {
return wholesaleRate;
}
public void setWholesaleRate(int wholesaleRate) {
this.wholesaleRate = wholesaleRate;
}
public int getSellingPrice() {
return SellingPrice;
}
public void setSellingPrice(int sellingPrice) {
SellingPrice = sellingPrice;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public newItem(int id, int wholesaleRate, int sellingPrice, int stock, String name) {
this.id = id;
this.wholesaleRate = wholesaleRate;
this.SellingPrice = sellingPrice;
this.stock = stock;
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试将 itemStr 作为主体发布到我在本地运行的 Restful API。我可以使用 GET 请求进行检索,但无法发布。
小智 10
OpenJDK 发布了桥接新 Java 11 HTTP 客户端和 Jackson 的方法: http://openjdk.java.net/groups/net/httpclient/recipes.html#jsonPost
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(map);
HttpRequest request = HttpRequest.newBuilder(uri)
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString(requestBody))
.build();
return HttpClient.newHttpClient()
.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::statusCode)
.thenAccept(System.out::println);
Run Code Online (Sandbox Code Playgroud)
希望杰克逊很快就能实现BodyPublisher自己,而不必先序列化为字符串......
| 归档时间: |
|
| 查看次数: |
13331 次 |
| 最近记录: |