gpt4 book ai didi

java - 如何修复从 REST 客户端使用 AZURE 表存储服务时指定的资源不存在错误

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:06 26 4
gpt4 key购买 nike

使用 Azure 存储表 REST 服务时遇到问题。即使资源存在于我的存储帐户中,在使用服务(插入实体)时也面临错误“指定的资源不存在”和 400 响应状态。

我尝试使用 Jersy Restful API 来使用 AZURE 存储服务 API。根据微软文档,我尝试使用该服务。文档链接:https://learn.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key

2) 我也尝试过 GET 操作...在这种情况下,响应返回 400 :reason=HTTP header 之一的值格式不正确。

3)当时也尝试了与 POSTMAN 相同的操作,也面临与上述相同的响应。

import java.net.*;
import java.util.*;
import java.text.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.codec.binary.Base64;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class InsertEntity_new {
private static Base64 base64 = new Base64();

public static void signRequestSK(WebTarget target, String account, String key, Client client) throws Exception {
ObjectMapper mapper = new ObjectMapper();
SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = fmt.format(Calendar.getInstance().getTime()) + " GMT";

StringBuilder sb = new StringBuilder();
sb.append("POST\n"); // method
sb.append('\n'); // md5 (optional)
sb.append('\n'); // content type
sb.append('\n'); // legacy date
sb.append("x-ms-date:" + date + '\n'); // headers
sb.append("x-ms-version:2009-09-19\n");
sb.append("/" + account + request.getURL().getPath()); //CanonicalizedResource

// System.out.println(sb.toString());
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(base64.decode(key), "HmacSHA256"));
String authKey = new String(base64.encode(mac.doFinal(sb.toString().getBytes("UTF-8"))));
String auth = "SharedKeyLite " + account + ":" + authKey;
client.property("x-ms-date", date);
client.property("Authorization", auth);
client.property("x-ms-version", "2009-09-19");


String jsonInString = "{\"PartitionKey\":\"mypartitionkey\",\"RowKey\":\"001\",\"Email\":\"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d1f0c00081e052d0a000c0401430e0200" rel="noreferrer noopener nofollow">[email protected]</a>\",\"PhoneNumber\":\"908265370\"}";
Response resp = target.request(MediaType.APPLICATION_JSON).post(Entity.entity(jsonInString, MediaType.APPLICATION_JSON));

System.out.println("Response" + resp);
}



public static void main(String args[]) throws Exception {
String account = "storageacctname";
String key = "storageaccountkey";

Client client = ClientBuilder.newClient();
WebTarget target = client.target("https://" + account + ".table.core.windows.net/mytable");
signRequestSK(target, account, key,client);

}
}

我希望我的程序需要将实体插入到我的存储表中。

最佳答案

ramesh。stringToSign 授权的两种格式略有不同。

共享 key 授权:

enter image description here

共享 key Lite 授权:

enter image description here

您将它们混合使用,这是不正确的。请引用我的工作代码如下(我使用Shared Key Lite授权):

package rest;

import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.json.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

public class InsertTableEntityTest {

private static final String account = "***";
private static final String key = "***";

public static void main(String args[]) throws Exception {

String urlString = "https://" + account + ".table.core.windows.net/jay";
System.out.println(urlString);

//prepare for the json body
JSONObject jsonObject = new JSONObject();
jsonObject.put("PartitionKey", "mypartitionkey");
jsonObject.put("RowKey", "myrowkey");

String jsonStr = jsonObject.toString();
String encoding = "UTF-8";
System.out.println(jsonStr);
byte[] data = jsonStr.getBytes(encoding);

HttpURLConnection conn = (HttpURLConnection) (new URL(urlString)).openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
getFileRequest(conn, account, data);
OutputStream outStream = conn.getOutputStream();

outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());

BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}

public static void getFileRequest(HttpURLConnection request, String account, byte[] data) throws Exception {
SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = fmt.format(Calendar.getInstance().getTime()) + " GMT";

String stringToSign = date + "\n" +
"/" + account + request.getURL().getPath();

System.out.println("stringToSign : " + stringToSign);
String auth = getAuthenticationString(stringToSign);
System.out.println(auth);
request.setRequestMethod("POST");
request.setRequestProperty("x-ms-date", date);
request.setRequestProperty("x-ms-version", "2013-08-15");
request.setRequestProperty("Authorization", auth);
request.setRequestProperty("Content-Length", String.valueOf(data.length));
request.setRequestProperty("Content-Type", "application/json");
request.setRequestProperty("Accept", "application/json");
}

private static String getAuthenticationString(String stringToSign) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(Base64.decode(key), "HmacSHA256"));
String authKey = Base64.encode(mac.doFinal(stringToSign.getBytes("UTF-8")));
// String auth = "SharedKey " + account + ":" + authKey;
String auth = "SharedKeyLite " + account + ":" + authKey;
return auth;
}
}

插入结果:

enter image description here

顺便说一句,x-ms-version 不是可选的(最新的是 2018-03-28 )来支持这种格式。请参阅Json format in table service .

关于java - 如何修复从 REST 客户端使用 AZURE 表存储服务时指定的资源不存在错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55510422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com