Java 使用Google HTTP客户端进行POST、PUT和DELETE操作

Java 使用Google HTTP客户端进行POST、PUT和DELETE操作,java,http,httpclient,Java,Http,Httpclient,如何使用Google HTTP客户端进行POST、PUT和DELETE操作: @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.setPath

如何使用Google HTTP客户端进行POST、PUT和DELETE操作:

@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();
    }
} 
@测试
public void testGetDBs()引发IOException{
GooUrl url=新的GooUrl(GOO_url);
列表路径=新建LinkedList();
添加(“用户”);
路径。添加(“id1”);
setPathParts(路径);
url.fields=“”;
HttpRequest请求;
试一试{
request=requestFactory.buildGetRequest(url);
request.setMethod(HttpMethod.POST);
字符串结果=request.execute().parseAsString();
System.out.println(“结果=”+结果);
}捕获(例外e){
e、 printStackTrace();
}
} 
假设我需要发布一个JSON字符串,怎么做?
另外,设置内容长度和类型。

您需要构建适当的类型请求,并在执行之前设置其内容

注意,在您的示例代码中,您正在构建一个GET请求,然后将该方法设置为POST,这很容易混淆。查看HttpRequestFactory代码,每个HTTP方法都有一个构建方法。尝试:

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();
似乎有几种不同类型的HttpContent可供选择(上面显示的是ByteArrayContent),当然,如果您发现HttpContent接口不能满足您的需要,您也可以自己实现它们