簡體   English   中英

什么是Java中的PHP CURLOPT_POSTFIELDS

[英]What is the equivalent of PHP's CURLOPT_POSTFIELDS in Java

我正在嘗試為putlokcer網站編寫一個上傳器類,他們有API支持。

根據他們的文檔,他們給出了如下的上傳示例

// Variables to Post
$local_file = "/path/to/filename.avi"; 
$file_to_upload = array(
    'file'=>'@'.$local_file, 
    'convert'=>'1', //optional Argument
    'user'=>'YOUR_USERNAME', 
    'password'=>'YOUR_PASSWORD', 
    'folder'=>'FOLDER_NAME'   // Optional Argument
); 

// Do Curl Request
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,'http://upload.putlocker.com/uploadapi.php'); 
curl_setopt($ch, CURLOPT_POST,1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $file_to_upload); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec ($ch); 
curl_close ($ch); 

// Do Stuff with Results
echo $result; 

現在我嘗試使用java.net包轉換Java,如下所示,

BufferedInputStream bis = null; BufferedOutputStream bos = null; 嘗試{URL url = new URL(“http://upload.putlocker.com/uploadapi.php”); URLConnection uc = url.openConnection(); uc.setDoOutput(真); uc.setDoInput(真); uc.setAllowUserInteraction(假);

        bos = new BufferedOutputStream(uc.getOutputStream());
        bis = new BufferedInputStream(new FileInputStream("C:\\Dinesh\\Naruto.jpg"));

        int i;

        bos.write("file".getBytes());

        // read byte by byte until end of stream
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }

        bos.write("user=myusername".getBytes());
        bos.write("password=mypassword".getBytes());
        br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String k = "",tmp="";
        while ((tmp = br.readLine()) != null) {
            System.out.println(tmp);
            k += tmp;
        }
    } catch (Exception e) {
        System.out.println(e);
    }

我收到響應“沒有有效的登錄或文件已通過”,這意味着,我的HTTP POST請求沒有發送有效的帖子文件。

誰能解釋我如何使用java.net包來完成這項工作?

在為表單帖子構建請求主體時,您必須遵循特定的格式,當您在PHP中使用curl時,會隱藏許多復雜性。 我建議你看看像這個問題的答案中描述的Apache HTTPComponents客戶端,而不是試圖推銷自己的。

(雖然如果你想手工完成,詳細信息在這個答案中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM