I am trying to create an Asset on Azure Media Services using REST API from Android. I am following this documentation and this is my code to connect with AMS endpoint from Android,
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();
And my _postData
variable is byte array which I am converting from 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");
I have tried using Google Chrome's REST api client extension to check the post request and It works fine. I got the response I was expecting from chrome's REST api client extension but using Android, I am not getting the same response. I am getting this response from this code which is the step I have already performed before running this code. I have used both endpoints https://media.windows.net/
and https://wamsbayclus001rest-hs.cloudapp.net/
but it is not working from Android. I believe that Android is changing Headers or something is wrong with headers that AMS not parsing properly. Can anyone guide me how to achieve this using Android HttpUrlConnection
?
Thanks.
I fixed it by changing OutputStream
to DataOutputStream
DataOutputStream wrr = new DataOutputStream(urlConnection.getOutputStream());
wrr.write(this._postData);
wrr.flush();
wrr.close();
and changed my json array to string,
String s = "{\"Name\":\"" + _fileName + ".mp4\", \"Options\":\"0\"}";
and it worked fine.