【问题标题】:Java rest calls with get parameters带有 get 参数的 Java REST 调用
【发布时间】:2014-12-31 01:01:49
【问题描述】:

如何在 java 中为 rest 调用添加参数或额外的行代码。

GET /ObjectName HTTP/1.1  
Host: BucketName.s3.amazonaws.com  
Date: date Authorization: authorization string (see Authenticating Requests (AWS  Signature Version 
4)) Range:bytes=byte_range

在 set 方法上将/Objectname 放在GET 之后会导致错误。

我使用的代码是;

public void getObject() throws Exception   {
  String fmt = "EEE, dd MMM yyyy HH:mm:ss ";
  SimpleDateFormat df = new SimpleDateFormat(fmt, Locale.US);
  df.setTimeZone(TimeZone.getTimeZone("GMT"));
  String ob2 = "/bucket/test.txt";
  String bucket = "/bucket";
  String method = "GET"; 
  String contentMD5 = "";
  String contentType = "";
  String date = df.format(new Date()) + "GMT";        

  // Generate signature
  StringBuffer buf = new StringBuffer();
  buf.append(method).append("\n");`enter code here`
  buf.append(contentMD5).append("\n");
  buf.append(contentType).append("\n");
  buf.append(date).append("\n");
  buf.append(ob2);   
  String signature = sign(buf.toString());

  HttpURLConnection httpConn = null;
  URL url = new URL("https”,”s3demo.s3demosite.com",443,bucket);
  httpConn = (HttpURLConnection) url.openConnection();
  httpConn.setDoInput(true);
  httpConn.setDoOutput(true);
  httpConn.setUseCaches(false);
  httpConn.setDefaultUseCaches(false);
  httpConn.setAllowUserInteraction(true);
  httpConn.setRequestMethod(method);
  httpConn.setRequestProperty("Date", date);
  httpConn.setRequestProperty("Content-Length", "0");
  String AWSAuth = "AWS " + keyId + ":" + signature;
  httpConn.setRequestProperty("Authorization", AWSAuth);

 // Send the HTTP PUT request.
 int statusCode = httpConn.getResponseCode();
 InputStream err = httpConn.getErrorStream();
 InputStream is = null;
 is = httpConn.getInputStream();
 int ch;
 StringBuffer sb = new StringBuffer();
 while ((ch = err.read()) != -1) {
  sb.append((char) ch);
 }
 if ((statusCode/100) != 2)
 {
    // Deal with S3 error stream.
    InputStream in = httpConn.getErrorStream();
    System.out.println("Error: "+errorStr);
 }
 else {
    System.out.println("download worked”);
 }
}

【问题讨论】:

  • 你能展示你目前使用的代码吗?
  • 你想传递一个参数给休息服务吗?

标签: java rest amazon-s3


【解决方案1】:

在 REST 服务中,您可以通过两种方式传递参数。

  1. 作为路径变量
  2. 作为查询参数。示例:GET /students/tomGET /students?name=tom

【讨论】:

  • 是的。我只是解释一下我们有两种方法可以将参数传递给 REST 服务。
  • 如果您看到添加的代码行 httpConn.setRequestMethod(method);它只会接受 GET POST 等。添加路径变量会导致程序错误。
  • 是的。它会报错。在 GET 请求参数中作为 URL 的一部分发送。
  • 为什么我们不能在 HttpURLConnection 中使用 POST。首先我们打开连接。然后我们可以将参数写入连接。有可能吗?
  • 对不起,我是新来的休息。您是说我可以发帖并执行 GET 来下载文件吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 2020-12-07
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
相关资源
最近更新 更多