android中的HTTP-PUT请求

时间:2014-12-25 21:45:44

标签: java android http curl

我想向Amazon S3发出HTTP-PUT请求。它适用于卷曲:

curl -v --upload-file file.jpg 'mybucket.amazonaws.com/avatars/cbe7e51de13c1cf93027ab7e14dbd910.jpg?Expires=1419615226&AWSAccessKeyId={MY_KEY}&Signature={MY_SIGNATURE}'

http标头如下所示:

PUT /avatars/cbe7e51de13c1cf93027ab7e14dbd910.jpg?Expires=1419615226&AWSAccessKeyId={MYKEY}&Signature={MYSIGNATURE} HTTP/1.1\r\n
User-Agent: curl/7.30.0\r\n
Host: mybucket.amazonaws.com\r\n
Accept: */*\r\n
Content-Length: 130485\r\n
    [Content length: 130485]
Expect: 100-continue\r\n
JPEG File Interchange Format

使用loopj我发送以下内容并获得403:

PUT /avatars/cbe7e51de13c1cf93027ab7e14dbd910.jpg?Expires=1419615226&AWSAccessKeyId={MYKEY}&Signature={MYSIGNATURE} HTTP/1.1\r\n
Content-Length: 130745\r\n
    [Content length: 130745]
Content-Type: multipart/form-data; boundary=86VaLUGmO9qAjHzA98n9F2K-5G812B\r\n
Host: mybucket.amazonaws.com\r\n
Connection: Keep-Alive\r\n
Accept-Encoding: gzip\r\n
MIME Multipart Media Encapsulation, Type: multipart/form-data, Boundary: "86VaLUGmO9qAjHzA98n9F2K-5G812B"

通过这样做:

            File myFile = new File("image.jpg");
            RequestParams params = new RequestParams();
            params.put("", myFile,"");
            client.put(MyApplication.getAppContext(),user.avatarUploadUrl, params, responseHandler);

如何发送像curl这样的请求用java(没有内容类型,没有多部分)? 因为这似乎对我有用。

2 个答案:

答案 0 :(得分:1)

我不确定主机应该是什么样子,但我相信通过这种实现,您可以发送任何您想要的请求。

        Socket s = new Socket();
    String host = "aws.amazon.com";
    PrintWriter s_out = null;
    BufferedReader s_in = null;

        try
        {
        s.connect(new InetSocketAddress(host , 80));
        System.out.println("Connected");

        //writer for socket
            s_out = new PrintWriter( s.getOutputStream(), true);
            //reader for socket
            s_in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        }

        //Host not found
        catch (UnknownHostException e) 
        {
            e.printStackTrace();
        }

        //Send message to server
    String Request = "your request";


    System.out.println("Request sent...");


    String response;
    while ((response = s_in.readLine()) != null) 
    {
        System.out.println( response );
    }

答案 1 :(得分:0)

这对我有用:

    File myFile = new File(file);
    RequestParams params = new RequestParams();
    params.put("", myFile);
    StringEntity stringEntity = new StringEntity("Content-Length" + String.valueOf(file.length()));
    FileEntity fileEntity = new FileEntity(myFile,"");
    client.put(MyApplication.getAppContext(), user.avatarUploadUrl, fileEntity, null, responseHandler);