使用HttpUrlConnection发布数据Java

时间:2012-02-09 11:50:34

标签: java upload httpurlconnection

我正在尝试通过他们的API将文件上传到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());
    }
}

1 个答案:

答案 0 :(得分:0)

我为我的项目使用了以下类。 http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/

它支持GET和POST请求。

您可以像

一样使用它
RestClient client = new RestClient(your_url);
client.AddParam("sub", "upload");
//Other parameters here

try { 
    client.Execute(RequestMethod.POST); 
} catch (Exception e) {}