import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;
import lombok.Data;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Main {
static JsonFactory JSON_FACTORY = new JacksonFactory();
static HttpRequestFactory httpRequestFactory = (new NetHttpTransport()).createRequestFactory();
public static void main(String[] args) throws IOException {
Map<String, Object> params = new HashMap<>();
params.put("id", 1234);
String url = "http://127.0.0.1:8080/user";
User map = postHttpRequest(url, params, User.class);
System.out.println(map);
}
private static <T> T postHttpRequest(String url, Map<String, Object> params, Class<T> clazz) throws IOException {
HttpRequest req = httpRequestFactory.buildPostRequest(
new GenericUrl(url),
new UrlEncodedContent(params));
req.setParser(new JsonObjectParser(JSON_FACTORY));
String json = req.execute().parseAsString();
return new ObjectMapper().readValue(json, clazz);
}
@Data
public static class User {
private String id;
}
}
I wrote it. The Google guy is simple, but I felt that there were few Post samples.
req.execute().parseAs(Map.class)
I could do something like that, so I thought it would work if I passed the class, but I could do Map, but I couldn't do normal vo. ..
So I used jackson.
Recommended Posts