---------------Part:1 ## passing JSON-Obj via a HttpPost Request---------------------
NOTE :: ## Include (json-lib-2.2.jar) for Creating a JsonObject ,etc..
private void callRestServices_JSON_Request(JSONObject jsonObj) {
String RestURL = "http://localhost:4040/RestServicesExample2/rest/JSONRequest/";
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response;
HttpPost httpPost;
StringEntity entity;
List<NameValuePair> regParams = new ArrayList<NameValuePair>();
try {
httpPost = new HttpPost(RestURL);
httpPost.setHeader("Accept", "application/json"); //Note this Step
httpPost.setHeader("Content-Type", "application/json"); //Note this Step
httpPost.setEntity(new StringEntity(jsonObj.toString())); //Note this Step
response = client.execute(httpPost);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String res = "";
while((res=br.readLine())!=null){
System.out.println( "response >>> "+response);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch(URISyntaxException e){
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
------------------Part:2 ## Consuming JSON-Obj via a HttpPost Request----------------
NOTE :: ## Do Include the requisite jar(json-simple-1.1.1.jar) for creating JsonObject & JsonParser ..
@POST
@Path("/JSONRequest")
@Consumes(javax.ws.rs.core.MediaType.APPLICATION_JSON) //Note this Step
public String receiveJSONobject_Testing(String requestParam){
String name = "";
String phone = "";
String email = "";
org.json.simple.JSONParser jsonParser = new JSONParser();
org.json.simple.JSONObject jsonObj = new JSONObject();
try {
jsonObj = (JSONObject) jsonParser.parse(requestParam);
name = jsonObj.get("name").toString();
phone = jsonObj.get("phone").toString();
email = jsonObj.get("email").toString();
} catch (ParseException e) {
e.printStackTrace();
}
String response = ("Response from RestService >>> name recevd = "+name +"phone recevd >> "+phone +" email recevd >> "+ email);
return response ;
}
-------------------------------------------------------------------------------------------------
No comments:
Post a Comment