如何将Hashtable添加到NameValuePair中?

时间:2013-02-19 00:42:25

标签: java android httpclient hashtable

我想添加一个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);

提前致谢!

2 个答案:

答案 0 :(得分:2)

您可以使用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));

答案 1 :(得分:2)

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

String message = "hello";

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

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

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

以下是manual

问题更新后更新的答案

如果您的HashTable值是一个字符串,那么您可以在nameValuePair

中添加它

new BasicNameValuePair("credit_card", (your_json))