Roshan
Roshan

Reputation: 2059

How to send POST request using HTTPClient with HashMap as one parameter

I want to send Post request with many string parameters along with one HashMap object. How to do this?

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
public class PostRequest {

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


      String url="http://url";      
      PostMethod post=new PostMethod(url);
      post.setParameter("param1","abc");
      post.setParameter("param2","1");
      HttpClient httpclient = new HttpClient();
      int a = httpclient.executeMethod(post);
      System.out.println("I::::::::::::::::" + a);      
      String postResp = post.getResponseBodyAsString();
      System.out.println("response::::" + postResp);      
    }
}

In the above code, I also want to send HashMap object in the request.

HashMap hm = new HashMap(); 
hm.put("key","value"); 
//Set this param in URL. 
post.setParameter("paramname",hm);

Please help.

Upvotes: 2

Views: 15084

Answers (4)

Paritosh
Paritosh

Reputation: 555

You can put all the strings in a HashMap, and then you can create a JSON object from it. After you can add this JSON to your post as post.setEntity(se); where se is StringEntity containing your JSON, like, StringEntity se = new StringEntity(json.toString());.

Now, you can pass 'post' to the executeMethod.

Upvotes: 0

Alin
Alin

Reputation: 314

Try to convert your hashmap to JSON string and put in post parameter. After that you can recreate your hashmap from that JSON string.

    Map<String, String> myMap = new HashMap<String, String>();
    myMap.put("MyKey", "MyValue");
    String jsonMap = new Gson().toJson(myMap);
    System.out.println(jsonMap);
    /*
     * output :{"MyKey":"MyValue"}
     */

    Map<String, String> myOriginalMap = new HashMap<String, String>();
    myOriginalMap = new Gson().fromJson(jsonMap, HashMap.class);
    System.out.println(myOriginalMap);
    /*
     * output : {MyKey=MyValue}`enter code here`
     */`enter code here`

Upvotes: 3

newuserua_ext
newuserua_ext

Reputation: 512

If i understood you correctly below changes will help you ;

PostMethod post=new PostMethod(url);
for (Entry<String, String> entry : map.entrySet()) {
    post.setParameter(entry.getKey(), entry.getValue());
}

Upvotes: 0

James Liu
James Liu

Reputation: 1

You can pass the hashMap as parameter in the method, and then foreach the hashMap while use the PostMethod.

Best Regards, James

Upvotes: -2

Related Questions