2012-02-09 67 views
0

我想通过他们的API使用Java将文件上传到Rapidshare。但我卡住了,我认为我的问题是他们的API不知道我上传的文件的属性名称,或类似的东西。它似乎上传并提交完美,但没有文件在我的帐户之后。发布数据Java与HttpUrlConnection

我根据我的代码是什么我发现这里:http://www.experts-exchange.com/Programming/Languages/Java/Q_20370019.html

如果任何帮助,我成功地创建使用PHP和卷曲的解决方案,但最终的解决方案必须在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()); 
    } 
} 
+0

你需要证明你的Java了。 – Jivings 2012-02-09 11:57:05

+0

加我的java源码 – 2012-02-09 12:02:24

+0

btw。错误是:“错误:子程序无效。(b6ba5d82)”,但我认为它指的是丢失的文件。 – 2012-02-09 12:45:40

回答