如何创建这样的Java HTTP请求格式?

时间:2018-08-27 15:06:22

标签: java amazon-web-services api http request

我需要创建一个Java应用程序,该应用程序将创建格式如下的PUT请求:

PUT /AccountId/vaults/VaultName HTTP/1.1
Host: glacier.Region.amazonaws.com
Date: Date
Authorization: SignatureValue
Content-Length: Length
x-amz-glacier-version: 2012-06-01

我对格式化请求还很陌生,因此可以得到任何帮助。我在代码中唯一拥有的就是:

public static void main(String[] args) {
        try {
            URL url = new URL("http://glacier.us-east-1.amazonaws.com");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("PUT");
            int code = con.getResponseCode();
            System.out.print(code);
        }

        catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

您可以说我很迷路。

1 个答案:

答案 0 :(得分:0)

您可以使用套接字来编写请求。 这样,您可以根据需要编写请求,只需要注意行结束符即可。

请参见以下示例:

package test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

public class Test {

    public static void main(String[] args) {

        try {

            String hostname = "glacier.us-east-1.amazonaws.com";
            int port = 80;

            InetAddress addr = InetAddress.getByName(hostname);
            Socket socket = new Socket(addr, port);
            // Send headers
            BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
            wr.write("PUT /AccountId/vaults/VaultName HTTP/1.1\n\r");
            wr.write("Host: glacier.Region.amazonaws.com\n\r");
            wr.write("Date: Date\n\r");
            wr.write("Authorization: SignatureValue\n\r");
            wr.write("Content-Length: Length\n\r");
            wr.write("x-amz-glacier-version: 2012-06-01\n\r");
            wr.write("\n\r");
            wr.flush();

            // Get response
            BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }

            wr.close();
            rd.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

通过上面的示例,我得到:

HTTP/1.1 500 Internal Server Error
Transfer-Encoding: chunked
Date: Mon, 27 Aug 2018 16:05:29 GMT
Connection: close

0

因此,该请求已“正确”发送。但是服务器上发生了什么事。

我希望它能帮助您,再见。