import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; /** * Send Get Request */ public void getRequest(String url) { HttpClient client = new HttpClient(); GetMethod getMethod = new GetMethod(url); try { int statusCode = client.executeMethod(getMethod); if (statusCode == HttpStatus.SC_OK) { //TODO } else { throw new Exception("Failed to get: " + getMethod.getResponseBodyAsString()); } } catch (Exception e) { logger.error(e); } finally { //release connection getMethod.releaseConnection(); } } /** * Send Post Request with JSON * @return JSON from Response */ private JsonObject postRequest(String url, JsonObject requestBody) { JsonObject responseJsonObj = null; HttpClient httpClient = new HttpClient(); PostMethod postRequest = new PostMethod(url); try { StringRequestEntity requestEntity = new StringRequestEntity(jsonString, "application/json", "UTF-8"); //set request body postRequest.setRequestEntity(requestEntity); //set request header postRequest.addRequestHeader("Content-Type", "application/json"); postRequest.addRequestHeader("Accept", "application/json"); //execute post request httpClient.executeMethod(postRequest); int statusCode = postRequest.getStatusCode(); if (statusCode == HttpStatus.SC_OK) { String postResponse = postRequest.getResponseBodyAsString(); JsonParser parser = new JsonParser(); responseJsonObj = (JsonObject) parser.parse(postResponse); } else { throw new Exception("Failed to post data: " + postRequest.getResponseBodyAsString()); } }catch (Exception ex) { logger.error(ex); } finally { //release connection postRequest.releaseConnection(); } return responseJsonObj; }
Note:
1. Here need to depend on "commons-httpclient.jar"
2. For post request, if request header not be set, may throw "General Error: Request method 'POST' not supported "