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

11,820

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`
Share:
11,820
Roshan
Author by

Roshan

merge keep

Updated on June 04, 2022

Comments

  • Roshan
    Roshan over 1 year

    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.

  • Roshan
    Roshan over 8 years
    No, I just want to set like this. HashMap hm = new HashMap(); hm.put("key","value"); Set this param in URL. post.setParameter("paramname",hm);
  • newuserua_ext
    newuserua_ext over 8 years
    as you see in API docs there is no such methods. hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/…