使用java.net.URL在Google App Engine中使用简单的RESTful Java客户端

时间:2013-03-10 21:10:51

标签: java google-app-engine rest

我正在 Google App Engine 中创建使用外部 RESTful 服务的网络应用。 经过一些研究后,我选择仅使用 java.net.URL 类,而不是使用任何JAX-RS API,例如 Jersey ,因为这些API具有一定的兼容性GAE的问题,或者只与某些版本兼容等等......我不太喜欢这个问题。

this tutorial之后,我要调用REST服务:

URL url = new URL("rest-service-url");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//process the response...

然后我使用Google's GSON处理JSON响应,它也与GAE完全兼容。

首先,您认为这是一个不错的选择吗?

然后,我想以某种方式集中这个代码,因为我的应用程序中有很多不同的服务调用,所以我怎么能这样做呢?我想用这样的方法创建一些类:

public BufferedReader sendRESTRequest (URL url)
    //previous code here...        
}

但我不确定......这种方法应该是静态的吗?同步?我应该在方法内还是在类中创建一个HttpURLConnection对象?等...

谢谢!

1 个答案:

答案 0 :(得分:0)

如果允许您为项目使用Apache库,请查看here。为什么重新发明轮子

的内容
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
private String poolTimeOutMillSecStr = System.getProperty("CONN_TIME_OUT_MILLSEC", "60000");

    private String maxTotalConnStr = System.getProperty("MAX_TOTAL_CONN", "400");

    private String maxConnPerRouteStr = System.getProperty("MAX_CONN_PER_ROUTE", "200");

    HttpUtility httpUtilty;

    private String baseUrl = System.getProperty("BASE_URL", "http://localhost:8888");

    private String userName;

    private String password;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        int poolTimeOutMillSec = Integer.parseInt(poolTimeOutMillSecStr);
        int maxTotalConn = Integer.parseInt(maxTotalConnStr);
        int maxConnPerRoute = Integer.parseInt(maxConnPerRouteStr);
        httpUtilty = new HttpUtility(poolTimeOutMillSec, maxTotalConn, maxConnPerRoute);
        httpUtilty.initialize(baseUrl);
        userName = "admin";
        password = "admin";

    }
}

并使用它

HttpResponse response = httpUtilty.postRequest(path, null, ins, null);
HttpEntity resEntity = response.getEntity();
相关问题