为什么Android HttpURLConnection无法使用REST API在Azure Media Services上创建资产?

时间:2017-06-03 17:12:59

标签: java android rest azure azure-media-services

我正在尝试使用Android的REST API在Azure Media Services上创建资产。我正在关注this documentation,这是我的代码,用于连接Android的AMS端点,

urlConnection = (HttpURLConnection) this._url.openConnection();
    urlConnection.setRequestProperty("Content-Type", String.valueOf("application/json"));
    urlConnection.setRequestProperty("DataServiceVersion", String.valueOf("1.0;NetFx"));
    urlConnection.setRequestProperty("MaxDataServiceVersion", String.valueOf("3.0;NetFx"));
    urlConnection.setRequestProperty("Accept", String.valueOf("application/json"));
    urlConnection.setRequestProperty("Accept-Charset", String.valueOf("UTF-8"));
    urlConnection.setRequestProperty("Authorization", String.format(Locale.ENGLISH, "Bearer %s", _token));
    urlConnection.setRequestProperty("x-ms-version", String.valueOf(2.11));
    urlConnection.setRequestProperty("x-ms-client-request-id", UUID.randomUUID().toString());
    urlConnection.setRequestProperty("Host", this._host);
    urlConnection.setRequestProperty("Content-Length", String.valueOf(this._postData.length));
    urlConnection.setRequestProperty("Expect", String.valueOf("100-continue"));

    urlConnection.setConnectTimeout(CONNECTION_TIME_OUT);
    urlConnection.setReadTimeout(CONNECTION_READ_TIME_OUT);
    urlConnection.setInstanceFollowRedirects(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);

    OutputStream wr= urlConnection.getOutputStream();
    wr.write(_postData);
    wr.flush();
    wr.close();

我的_postData变量是我从json转换的字节数组,

_fileName = _fileName.replace(" ", "-");

    JSONObject jo = new JSONObject();
    jo.put("Name", _fileName+".mp4");
    jo.put("Options", String.valueOf(0));

    this._postData = jo.toString().getBytes("UTF-8");

我尝试使用Google Chrome的REST api客户端扩展来检查发布请求,但它运行正常。我得到了我期望从chrome的REST api客户端扩展中得到的响应但是使用Android,我没有得到相同的响应。我从这段代码中得到this response,这是我在运行此代码之前已经执行的步骤。我使用了两个端点https://media.windows.net/https://wamsbayclus001rest-hs.cloudapp.net/,但它无法在Android上运行。我相信Android正在改变标题或AMS无法正确解析的标题出现问题。任何人都可以使用Android HttpUrlConnection指导我如何实现这一目标吗?

感谢。

1 个答案:

答案 0 :(得分:0)

我通过将OutputStream更改为DataOutputStream

来修复此问题
DataOutputStream wrr = new DataOutputStream(urlConnection.getOutputStream());
        wrr.write(this._postData);
        wrr.flush();
        wrr.close();

并将我的json数组更改为string,

String s = "{\"Name\":\"" + _fileName + ".mp4\", \"Options\":\"0\"}";

它工作正常。