简体   繁体   中英

How can I add a Hashtable into a NameValuePair?

I want to add a Hashtable as the value of a NameValuePair as follows:

name= credit_card

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

or like this:

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

This is part of my code and you can you can see how I'm adding a simple 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);

Thanks in advance!

You can use Apache DigestUtils to compute a hash very easily:

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

Or you could use the Java Cryptography API directly:

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));

I am not sure I am understanding your question properly. But I am giving a try here-

String message = "hello";

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

So you can modify your add method of nameValuePairs something like below.

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

Here is the manual

Updated Answer after question is updated

If you HashTable value is a String then you can add it like this in your nameValuePair

new BasicNameValuePair("credit_card", (your_json))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM