从Android连接到Azure DocumentDB

时间:2015-02-22 05:17:04

标签: android azure azure-cosmosdb

有没有人有经验从android连接到Azure的documentdb?我尝试过使用新的Java SDK,但由于核心android SDK中存在一些旧的必需的Apache依赖冲突,因此它似乎在android中得不到支持。我正在尝试Rest API方法,但它进展缓慢。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:6)

好的,这是一个要解决的噩梦。九个小时后...... -_-'。简而言之,这里有一些实际上可以成功运行的代码。此代码并不完美,并且依赖于Retrofit

首先,这是Retrofit中的“服务”界面:

import retrofit.Callback;
import retrofit.http.Body;
import retrofit.http.Header;
import retrofit.http.POST;

public interface MyPojoService {
    @POST("/dbs/[db_id]/colls/[collection_id]/docs")
    void addDocument(@Header("authorization") String authorization, @Header("x-ms-date") String date, @Body MyPojo myPojo, Callback<MyPojo> cb);
}

接下来,我们在类中将初始设置字段调用DocumentDB:

// Replace with your DocumentDB master key.
private static final String MASTER_KEY = "[Insert Key Here]";

//Gson instance.
private Gson gson = new Gson();

现在我们将拥有针对RESTful端点执行的方法:

public void callDocumentDB() {
    SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    String headerDate = formatter.format(new Date()).toLowerCase();  //According to the spec the format matters here.  Make sure to use this format on the header dates.


    MyPojo myPojo = new MyPojo();
    myPojo.id = UUID.randomUUID().toString(); //This is the only required field, and does not have to be a UUID.

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint("https://[INSERT DB NAME HERE].documents.azure.com")
            .build();

    MyPojoService service = restAdapter.create(MyPojoService.class);

    service.addDocument(generateAuthHeader("post", "docs", "[INSERT COLLECTION ID HERE]", headerDate, MASTER_KEY), headerDate, myPojo, new Callback<MyPojo>() {
        @Override
        public void success(MyPojo myPojo, Response response) {
            //[INSERT API SUCCESSFUL CALL LOGIC HERE]
        }

        @Override
        public void failure(RetrofitError error) {
            throw error;
        }
    });
}

最后,我们有生成授权标头的方法。这种方法是一个整合的噩梦,但它适用于规范:

private String generateAuthHeader(String verb, String resourceType, String resourceId, String date, String masterKeyBase64) throws Exception
{
    //Decode the master key, and setup the MAC object for signing.
    byte[] masterKeyBytes = Base64.decode(masterKeyBase64, Base64.NO_WRAP);
    Mac mac = Mac.getInstance("HMACSHA256");
    mac.init(new SecretKeySpec(masterKeyBytes, "HMACSHA256"));

    //Build the unsigned auth string.
    String stringToSign = verb + "\n"
            + resourceType + "\n"
            + resourceId + "\n"
            + date + "\n"
            + "\n";

    //Sign and encode the auth string.
    String signature = Base64.encodeToString(mac.doFinal(stringToSign.toLowerCase().getBytes("UTF8")), Base64.NO_WRAP);

    //Generate the auth header.
    String authHeader = URLEncoder.encode("type=master&ver=1.0&sig=" + signature, "UTF8");

    return authHeader;
}

注意:请注意,generateAuthString和MyPojoService设置为使用x-ms-date标头而不是日期标头。当前版本的Azure的DocumentDB存在一个错误,似乎是保持生成的令牌无法正确授权。

我希望这会有所帮助,并为您节省一些时间。