1. 程式人生 > >使用Java語言編寫的Demo:上傳檔案至百度網盤(Baidu PCS)

使用Java語言編寫的Demo:上傳檔案至百度網盤(Baidu PCS)

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class PCSUploadDemo {

    //post請求地址
    private final static String API = "https://pcs.baidu.com/rest/2.0/pcs/file";

    //本地檔案路徑, 例如:"/Users/macuser/Documents/workspace/test.jpg"
    private static String mLocalPath;

    //上傳檔案路徑(含上傳的檔名稱), 例如:"/apps/yuantest/test.jpg"
    private static String mDestPath;

    //開發者准入標識 access_token, 通過OAuth獲得
    private static String mAccessToken;

    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("Usage: PCSUploadDemo file_to_upload destination your_access_token");
            return;
        }

        mLocalPath = args[0];
        mDestPath = args[1];
        mAccessToken = args[2];

        File fileToUpload = new File(mLocalPath);
        if (!(fileToUpload).isFile()) {
            System.out.println("Input file_to_upload is invalid!");
            return;
        }

        System.out.println("Uploading...");

        Thread workerThread = new Thread(new Runnable() {
            public void run() {						    		
                try {
                    doUpload();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        workerThread.start();

        return ;
    }

    public static void doUpload() throws IOException{
        File fileToUpload = new File(mLocalPath);

        if(null != fileToUpload && fileToUpload.length() > 0){

            ArrayList params = new ArrayList();
            params.add(new BasicNameValuePair("method", "upload"));
            params.add(new BasicNameValuePair("access_token", mAccessToken));
            params.add(new BasicNameValuePair("path", mDestPath));

            //新增請求引數,通過POST表單進行傳遞,除上傳檔案內容之外的其它引數通過query_string進行傳遞。
            String postUrl = API + "?" + buildParams(params); 

            HttpPost post = new HttpPost(postUrl);

            //新增檔案內容,必須使用multipart/form-data編碼的HTTP entity
            MultipartEntity entity = new MultipartEntity();
            FileBody fo = new FileBody(fileToUpload);
            entity.addPart("uploaded",fo);
            post.setEntity(entity);

            //建立client
            HttpClient client = new DefaultHttpClient();

            //傳送請求
            HttpResponse response = client.execute(post);

            System.out.println(response.getStatusLine().toString());
            System.out.println(EntityUtils.toString(response.getEntity()));

        }		    
    }

    // url encoded query string
    protected static String buildParams(List urlParams){		
        String ret = null;		
        if(null != urlParams && urlParams.size() > 0){			
            try {
                // 指定HTTP.UTF_8為charset引數以保證中文檔案路徑的正確
                HttpEntity paramsEntity = new UrlEncodedFormEntity(urlParams, HTTP.UTF_8);
                ret = EntityUtils.toString(paramsEntity);
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }		
        return ret;
    }
}