3

I am trying to write a uploader class for putlokcer website and they have API support.

As per their documentation, they gave an upload example as follows

// 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; 

Now I am trying to convert in terms of Java using java.net package as follows,

BufferedInputStream bis = null; BufferedOutputStream bos = null; try { URL url = new URL("http://upload.putlocker.com/uploadapi.php"); URLConnection uc = url.openConnection(); uc.setDoOutput(true); uc.setDoInput(true); uc.setAllowUserInteraction(false);

        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);
    }

I am getting response as "No valid login or file has been passed" which means, my HTTP POST request doesn't sent with valid post fileds.

Can anyone explain me how to get this work with java.net package?

Dinesh
  • 14,859
  • 20
  • 72
  • 113

1 Answers1

1

There are specific formats you have to follow when building up the request body for a form post, there's a lot of complexity which is hidden from you when you use curl in PHP. I suggest you look at something like the Apache HTTPComponents client as described in the answers to this question rather than trying to roll your own.

(Though if you do want to do it by hand the details are in this answer)

Community
  • 1
  • 1
Ian Roberts
  • 114,808
  • 15
  • 157
  • 175