【问题标题】:How can I add a Hashtable into a NameValuePair?如何将 Hashtable 添加到 NameValuePair 中?
【发布时间】:2013-02-03 13:39:50
【问题描述】:

我想添加一个 Hashtable 作为 NameValuePair 的值,如下所示:

name= credit_card

value(this is the hashtable)= {expirationDate="2013/02/18", ownerName="Jack Sparrow", typeOfCard="C2"}

或者像这样:

new BasicNameValuePair("credit_card",{expirationDate="2013/02/18", ownerName="Jack Sparrow", typeOfCard="C2"})。

这是我的代码的一部分,你可以看到我是如何添加一个简单的 NameValuePair 的:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://example.com/register");
try {
  List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
  nameValuePairs.add(new BasicNameValuePair("user", user));
  nameValuePairs.add(new BasicNameValuePair("password", password));
  post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

  HttpResponse response = client.execute(post);

提前致谢!

【问题讨论】:

  • “添加哈希”是什么意思?
  • hash 你在说什么?
  • 问题已编辑,谢谢!
  • 如您所见,BasicNameValuePair 构造函数是 BasicNameValuePair(String name, String value) hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/…
  • @Carlos - 您是否尝试使用键“credit_card”添加 JSON 字符串的哈希值,作为 BasicNameValuePair?基本上是 new BasicNameValuePair("credit_card", hash(json))?

标签: java android httpclient hashtable


【解决方案1】:

您可以使用Apache DigestUtils 轻松计算哈希:

String hash = DigestUtils.sha512Hex(json);
nameValuePairs.add(new BasicNameValuePair("credit_card", hash));

或者您可以直接使用 Java Cryptography API:

final Charset charset = Charset.forName("UTF-8");
final MessageDigest digest = MessageDigest
        .getInstance("SHA-512");
final byte[] hashData = digest
        .digest(json.getBytes(charset));
final String hash = new String(hashData, charset);
nameValuePairs.add(new BasicNameValuePair("credit_card", hash));

【讨论】:

    【解决方案2】:

    我不确定我是否正确理解了您的问题。但我在这里试一试-

    String message = "hello";

    System.out.println( DigestUtils.md5Hex(message) );

    因此您可以修改nameValuePairsadd 方法,如下所示。

    new BasicNameValuePair("credit_card", DigestUtils.md5Hex(your_json))

    这里是manual

    问题更新后更新答案

    如果你的 HashTable 值是一个字符串,那么你可以像这样在你的 nameValuePair 中添加它

    new BasicNameValuePair("credit_card", (your_json))

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      相关资源
      最近更新 更多