quocvuongdn icon

#java: send POST with specified data fields

quocvuongdn | PRO | 09/22/14 08:20:43 AM UTC | 0 ⭐ | 450 👁️ | Never ⏰ | []
Java |

1.58 KB

|

None

|

0 👍

/

0 👎

public String sendPost(Map<String, NameValuePair> paramList, String paramNames){
        String json_result = "";
 
        List<NameValuePair> input = new ArrayList<>();
        String[] split = paramNames.split(",");
        for (String str : split) {
            if (paramList.get(str.trim()) != null) {
                input.add(paramList.get(str.trim()));
            }
        }
        
        String query = URLEncodedUtils.format(input, "utf-8");
        
        //Create post http client
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(ME_URL+query);
        try {
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity resEntity = response.getEntity();
 
                if (resEntity != null) {
                    json_result = EntityUtils.toString(resEntity);
                } else{
                    json_result = ME_URL + query;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(ProcessRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
        return json_result;
    }
 
// Using HttpClient 4.3 lib
//Input:
//paramList: MAP<String KEY, BasicNameValuePair INPUT_PARAM>
//paramNames: String of specified fields, ex: name, age, value.
//This func plays a mediating role in the connection between a client and a server.
 
//Client A send somedata (ex: name, age, address, job) << sendPOST filter data fields and CURL to >> Server B receive only specified data fields (ex: name, age, address)

Comments