Reputation:
How to do POST, PUT and DELETE with Google HTTP Client:
@Test
public void testGetDBs() throws IOException {
GooUrl url = new GooUrl(GOO_URL);
List<String> path = new LinkedList<String>();
path.add("users");
path.add("id1");
url.setPathParts(path);
url.fields = "";
HttpRequest request;
try {
request = requestFactory.buildGetRequest(url);
request.setMethod(HttpMethod.POST);
String result = request.execute().parseAsString();
System.out.println("Result = " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
Say I need to do POST a JSON string, how to do that? Also, set the content length and type.
Upvotes: 5
Views: 4434
Reputation: 161
You need to build the appropriate type request and set its content before executing.
Note that in your example code, you are building a GET request, and then setting the method as POST, which is confusing. Looking at the HttpRequestFactory code, there is a build method for each HTTP method. Try:
final request = requestFactory.buildPostRequest(url);
final byte [] contentBytes = ...//get some bytes!!
final HttpContent content = new ByteArrayContent("application/json", contentBytes );
request.setContent( content );
final String result = request.execute().parseAsString();
There appear to be several different types of HttpContent to choose from (ByteArrayContent is shown above), and of course you can probably implement the HttpContent interface yourself if you find they do not meet your needs.
Upvotes: 7