【发布时间】:2012-02-09 11:50:34
【问题描述】:
我正在尝试通过他们的 API 使用 Java 将文件上传到 Rapidshare。但我被卡住了,我认为我的问题是他们的 API 不知道我上传文件的属性名称,或者类似的东西。似乎它上传和提交完美,但之后我的帐户中没有文件。
我的代码基于我在此处找到的内容:http://www.experts-exchange.com/Programming/Languages/Java/Q_20370019.html
如果有帮助,我成功地使用 PHP 和 cURL 创建了一个解决方案,但最终的解决方案必须是 Java。
$post = array(
'sub' => 'upload',
'login' => $user,
'password' => $pass,
'filecontent' => '@'. $filepath
);
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_URL, 'https://rs'. $server .'.rapidshare.com/cgi-bin/rsapi.cgi');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $post);
$info = curl_exec($c);
curl_close($c);
我的 Java 源代码:
package main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String args[]) throws Exception {
String url = "http://rs"+ getServerId() +".rapidshare.com/cgi-bin/rsapi.cgi?sub=upload&login=***&password=***";
String docPath = "/Users/***/Downloads/a.jpg"; // Document
HttpURLConnection httpcon = (HttpURLConnection) ((new URL(url).openConnection()));
httpcon.setDoOutput(true);
httpcon.setUseCaches(false);
httpcon.setRequestProperty("Content-Type", "multipart/form-data");
httpcon.connect();
System.out.println("Posting " +docPath +"...");
File file = new File(docPath);
FileInputStream is = new FileInputStream(file);
OutputStream os = httpcon.getOutputStream();
// POST
// Read bytes until EOF to write
byte[] buffer = new byte[4096];
int bytes_read; // How many bytes in buffer
while((bytes_read = is.read(buffer)) != -1) {
os.write(buffer, 0, bytes_read);
}
os.close();
is.close();
System.out.println("Done...");
}
private static int getServerId() throws NumberFormatException, IOException {
HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(
"http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=nextuploadserver")
.openConnection();
httpUrlConnection.connect();
InputStreamReader in = new InputStreamReader(
(InputStream) httpUrlConnection.getContent());
BufferedReader buff = new BufferedReader(in);
return Integer.parseInt(buff.readLine());
}
}
【问题讨论】:
-
你也需要展示你的 Java。
-
顺便说一句。错误是:“错误:子程序无效。(b6ba5d82)”但我认为它指的是丢失的文件。
标签: java upload httpurlconnection