I tried to upload a video file programmatically to Twitch. I following the instruction on https://dev.twitch.tv/docs/video-upload/, and was successfully created a video using the API, however, when uploading it, I got error code 400, but no error message. My test code is attached. Can anyone give me some insight on what is missing? Many thanks!
// HTTP POST request
private void uploadVideo(String uploadUrl, String token, String videoFile) throws Exception {
String boundary = createBoundary();
String LINE_FEED = "\r\n";
String url = uploadUrl + "?index=1&upload_token=" + URLEncoder.encode(token, "UTF-8");
try {
URL putUrl = new URL(uploadUrl + "?index=1&upload_token=" + token);
HttpURLConnection httpCon = (HttpURLConnection) putUrl.openConnection();
//httpCon.setRequestProperty("Content-Length", "" + data.length);
httpCon.setUseCaches(false);
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
httpCon.setRequestProperty("User-Agent", "Java IPFS CLient");
httpCon.setRequestMethod("PUT");
// set some connection properties
OutputStream output = httpCon.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, CHARSET), true);
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: file; filename=\"" + videoFile + "\"").append(LINE_FEED);
writer.append("Content-Type: application/octet-stream").append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
InputStream inputStream = new FileInputStream(videoFile);
byte[] buffer = new byte[4096];
int r;
while ((r = inputStream.read(buffer)) != -1)
output.write(buffer, 0, r);
output.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
StringBuilder b = new StringBuilder();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
int status = httpCon.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpCon.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
b.append(line);
}
reader.close();
httpCon.disconnect();
} else {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpCon.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
b.append(line);
}
reader.close();
} catch (Throwable t) {}
throw new IOException("Server returned status: " + status + " with body: "+b.toString() + " and Trailer header: "+httpCon.getHeaderFields().get("Trailer"));
}
System.out.println("Server response status code is " + status + "; message is " + b.toString());
}
catch(Exception e)
{
e.printStackTrace();
}
}