简体   繁体   中英

Do POST, PUT and DELETE with Google HTTP Client

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM