简体   繁体   English

Java:发送POST HTTP请求以将文件上传到MediaFire REST API

[英]Java: send POST HTTP request to upload a file to MediaFire REST API

I need to send a HTTP POST request to the MediaFire REST API from a Java web app running in Google App Engine , in order to upload a file. 我需要从运行在Google App Engine中Java Web应用程序MediaFire REST API发送HTTP POST请求 ,以便上传文件。

Please see upload function documentation here (few lines). 在此处查看上传功能文档(几行)。

Looking at the documentation and some research, I've written the following Java code to make the correspondent request: 查看文档和一些研究,我编写了以下Java代码来提出相应的请求:

byte[] bytesData = //byte array with file data

URL url = new URL("http://www.mediafire.com/api/upload/upload.php?" +
                    "session_token=" + sessionToken);

//Configure connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setReadTimeout(60000);

//Set headers
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestProperty("x-filename", fileName);
conn.setRequestProperty("x-filesize", fileSize);
conn.setRequestProperty("x-filehash", sha256);

//Write binary data
System.out.println("\nWriting data...");
OutputStream out = conn.getOutputStream();
out.write(bytesData);
out.flush();

//Check connection
//if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
//  throw new RuntimeException("FAILED!!! HTTP error code: " + 
//                             conn.getResponseCode() + " --- " + 
//                             conn.getResponseMessage());
//}

//Get response
System.out.println("\nGetting response...");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

//Print response
System.out.println("\nOutput from Server .... \n");
String output;
while ((output = br.readLine()) != null) {
  System.out.println(output);
}

But I'm not getting any result, just: 但是我没有任何结果,只是:

Writing data...
Getting response...
Output from Server:

If I un-comment the lines under //Check connection I get an Exception : 如果取消注释 //Check connection下的行,则会出现Exception

java.lang.RuntimeException: FAILED!!! HTTP error code: 503 --- OK

If I change the Content-Type header for multipart/form-data I get a different Exception : 如果我更改multipart/form-dataContent-Type标头, multipart/form-data得到另一个Exception

java.lang.RuntimeException: FAILED!!! HTTP error code: 400 --- OK

I don't know too much about HTTP connections and so on and I have no idea about what's happening... 我对HTTP连接等不了解太多,也不知道发生了什么...

Any ideas about what may be going on? 关于可能会发生什么的任何想法?


Note : I'm using other (GET) methods of the API from the same app and they are working perfectly. 注意 :我正在使用同一应用程序中API的其他(GET)方法,它们运行良好。

HTTP错误代码:400是错误请求的状态代码,这可能意味着服务器除了multipart / form-data以外,503代码意味着服务器超载,因此该服务可能托管在服务器上的其他服务器/线程上其他GET方法,可能会收到更多流量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM