HttpServletRequest JSON parameter found null value in Servlet - java

I'm using Servlet to handle request and response.
I have used following code to Servlet my request to sublet using webservice:
JSONObject parans = new JSONObject();
parans.put("commandid", "Enamu7l");
System.out.println("parans = " + parans);
Client restClient = Client.create();
WebResource webResource = restClient.resource("URL");
ClientResponse resp = webResource.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, parans.toJSONString());
Here is my servlet code to receive data.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String commandid= request.getParameter("commandid");
System.out.println(commandid);
}
commandid recieve null from webservice.
What to do in webservice to get data in servlet?

WebResource not sending the data as part of the url, so you can not use request.getParameter. The data is send as request body using the post method.Read the data using the reader.
StringBuilder sb = new StringBuilder();
while ((s = request.getReader().readLine()) != null) {
sb.append(s);
}
JSONObject jSONObject = new JSONObject(sb.toString());
System.out.println(jSONObject.getString("commandid"));

You are sending JSON in request body, so you need to get it:
String json = request.getReader().lines().collect(Collectors.joining());
Convert to JSON:
JSONObject jsonObject = new JSONObject(json);
And get the value:
String value = jsonObject.getString("commandid");

Related

How to pass dynamic value inside Request body

I have two tokens one is brandwiseBearerToken which is a string and another is thirdPartyPaymentGatewayToken it belongs form my POJO class, and I want to pass these two values as dynamic. but in my case, I pass as hard-coded how I can make it dynamic. for your reference, I share my code.
I want to dynamic exact at this point
String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);
RequestBody body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson);
I don't want to pass hard-coded data
public ThirdPartyPaymentGatewayResponse getThirdPartyPaymentGatewayToken(ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken, String managedBy)
throws AuthenticationException, UnknownHostException, BadRequestException {
String brandwiseBearerToken = authenticationToken();
String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);
RequestBody body = RequestBody.create(mediaType, thirdPartyPaymentGatewayTokenJson);
Request request = new Request.Builder().url(brandwiseThirdPartypaymentGatewayURL)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Bearer", brandwiseBearerToken)
.build();
Response response = client.newCall(request).execute();
ResponseBody responseBody = response.body();
JsonObject jsonObject = new Gson().fromJson(responseBody.string(), JsonObject.class);
JsonElement error = jsonObject.get("Message");
}
```

JSON Request via okhttp with Java and PHP

I am using okhttp lib with Java and PHP. My Java client is running the following code.
public class Connection {
public static final MediaType JSON = MediaType
.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).post(body).build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static void main(String[] args) throws IOException {
Connection example = new Connection();
String json = "{'input':'test'}";
String response = example.post("http://localhost/android_api/index.php", json);
System.out.println(response);
}
}
On the server-side I try to decode the JSON String with code following below but my webservice just return a NULL.
<?php
$rawData = file_get_contents("php://input");
$json = json_decode($rawData);
var_dump($json);
?>
What am I doint wrong?
First, you are calling an http request on the main-thread which will cause an error. So you use AsyncTask

How to return JSON object to AngularJS using Java Servlet

I have to write a controller in my project using servlets. I've done it before but I've never worked with AngularJS, so I did it via request.setAttribute() and request.getParameter() and put Java code inside of a JSP page. But now frontend developer used AngularJS and I have to return him a JSON object. And I have no idea how to do it. Here's the code of abTestCtrl.js:
app.controller("abTestCtrl", function($scope, $location, $http) {
$scope.title = "no title";
$scope.description = "no description";
$scope.getParam = $location.search()['id'];
if($scope.getParam === undefined)$scope.getParam = 0;
//$scope.getParam=2;
//path: localhost8080/UIUM.../servlet-name.java
//with two ids
//web.xml: serverlet mapping for the path
if($scope.getParam==='0'||$scope.getParam === 0){
var saveButton = document.getElementById("saveButton");
saveButton.classList.remove("hidden");
}
else{
$http.get('http://localhost:8080/UIUM_IMT4003/ABTestController', {command:'getTestCaseInfo', testcaseID:$scope.getParam}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log('request succesful');
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('request not succesful');
});
}
and my processRequest() code from the servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ClassNotFoundException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json; charset=UTF-8");
//PrintWriter printout = response.getWriter();
JSONObject jObject = null;
RequestDispatcher view = null;
TestcaseRepository testcaseRepo = new TestcaseRepository();
String command = request.getParameter("command");
if(command == null)
{
view = request.getRequestDispatcher("/testcases.jsp");
view.forward(request, response);
}
if(command.equals("getTestCaseInfo")){
String testcaseId = request.getParameter("testcaseID");
Testcase testcase = testcaseRepo.getTestcaseById(testcaseId);
jObject = new JSONObject();
jObject.put("id", testcaseId);
jObject.put("title", testcase.getTestcaseName());
jObject.put("testscenario", testcase.getTestcaseDescription());
// printout.print(jObject);
// printout.flush();
jObject.write(response.getWriter());
}
Can you please help me to process this request and finally return this poor JSON!
BTW, Servlet doesn't recognize command parameter. It gets null. But there is such parameter in AngularJS function.
Try using the javax.json.JsonObject as follow:
JsonObject jo=Json.createObjectBuilder()
.add("id", testcaseId)
.add("title", testcase.getTestcaseName())
.add("testscenario", testcase.getTestcaseDescription()).build();
Then set the response content type to json and send your json object in the response:
response.setContentType("application/json");// set content to json
PrintWriter out = response.getWriter();
out.print(jo);
out.flush();

Retrieving dynamic JSONObject value from server response in servlets

Hi I am getting the access_token value dynamically from server for servlet request it is below: now i want to retrive the access_taken value in to my servlet program.
{
"access_token":"AQWP_EVkqdc7E0wD09J6msmjnUlvilhP304gUIDzl6KKgNxwnHyz_W9nOxS0IroDJwEfVr3n3O-IC9YKc3bjyuwYRm6qbKRiP3A2AzuDjo8ohZERZFRCMyfjjqqDjNJ5J5ReCQDhkFJam51eiqsOeXDg4U_c9XJzc1dUx7Qxck0p9RNE0",
"expires_in": 5183999
}
my code is below:
public class Demo extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String PROTECTED_RESOURCE_URL = "http://api.linkedin.com/v1/people/~:(first-name,last-name,email-address)";
/**
* #see HttpServlet#HttpServlet()
*/
public Demo() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out=response.getWriter();
String authCode = request.getParameter("code");
request.setAttribute("authCode",authCode);
out.println(authCode);
doPost(request,response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out=response.getWriter();
Object url=request.getAttribute("authCode");
response.sendRedirect("https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code="+url+"&redirect_uri=http://localhost:8080/LinkedinMails/dem&client_id=xxxxxxxxxxxxx&client_secret=xxxxxxxxxxxxxxx");
}
}
Thank You.
public String doGet(String url) throws Exception {
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
String line;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
conn.disconnect();
return buffer.toString();
}
Now you can call this method from your servlet to get server response in servlet. Hope it will useful to you.
You can use Gson or Jackson libraries for conveting your JSON response.
Using Jackson:
new ObjectMapper().readValue(result, LinkedIn.class);
where result is your JSON that contains access_Token and expires_in
LinkedIn.java
#JsonIgnoreProperties(ignoreUnknown=true)
public class LinkedIn
{
#JsonProperty("access_token")
private String accessToken;
#JsonProperty("expires_in")
private long expiresIn;
// Getters and setters for expiresOn and accessToken
}
In your Servlet/Controller
LinkedIn l= new ObjectMapper().readValue(result, LinkedIn.class); // Result is your JSON response which has access token and expires from LinkedIn
l.getAccessToken() ; // Returns you access token
l.getExpiresIn() // Returns you the expires time frame
}
Using JSONObject
String s="{\n" +
" \"access_token\":\"AQWP_EVkqdc7E0wD09J6msmjnUlvilhP304gUIDzl6KKgNxwnHyz_W9nOxS0IroDJwEfVr3n3O-IC9YKc3bjyuwYRm6qbKRiP3A2AzuDjo8ohZERZFRCMyfjjqqDjNJ5J5ReCQDhkFJam51eiqsOeXDg4U_c9XJzc1dUx7Qxck0p9RNE0\",\n" +
" \"expires_in\": 5183999\n" +
"}"; // This contains your access token JSON
JSONParser parser = new JSONParser();
JSONObject o = (JSONObject) parser.parse(s);
System.out.println("Access Token: "+o.get("access_token")); //returns your access token
System.out.println("Expires: "+o.get("expires_in"));
Getting the Access Token JSON:
In your Demo Servlet, doPost method, instead of sendRedirect do a
http Post (Using Apache Http Client or java.net)call to the url.
Once the HTTP Post is done, You get back a Http response which will be application/json content. So get this String content (which contains application/json). This string content is your access_token sent to you by LinkedIn. Once you get back the response, do this:
JSONParser parser = new JSONParser();
JSONObject o = (JSONObject) parser.parse(responseString); // responseString is the JSON that you got from LinkedIn.
System.out.println("Access Token: "+o.get("access_token")); //returns your access token
System.out.println("Expires: "+o.get("expires_in"));

How To Receive JSON Data In Cross Origin Resource Sharing (CORS) with Spring REST

I am trying to send / Receive JSON data from / to my Controller Class in my Project.
The Controller Class Of My Project Is as Follows :
#RequestMapping(value = "/dummy/",method = RequestMethod.POST,headers="Accept=application/json")
public Response getDummyJSON() {
/* Method 2: Getting the Dummy JSON Data From file and sending it as an JSON Object */
JSONParser parser = new JSONParser();
JSONObject jsonObject = null;
try {
Object obj = parser.parse(new FileReader("d:\\JsonStruc.json"));
jsonObject = (JSONObject) obj;
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
return Response.status(200).entity(jsonObject).build();
}
#RequestMapping(value = "/insert/dummy/",method= RequestMethod.POST,headers="Accept=application/json")
public Response setDummyJSON(#RequestBody JSONObject inputjsonObj){
/*Step 1: Display The JSON data sent by AngularJS */
System.out.println("Data Received:"+ inputjsonObj.toString());
JSONParser jsonparser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory(){
public List creatArrayContainer() {
return new LinkedList();
}
public Map createObjectContainer() {
return new LinkedHashMap();
}
};
Map obj = (Map)inputjsonObj;
Iterator iter = obj.entrySet().iterator();
while(iter.hasNext()){
Map.Entry entry = (Map.Entry)iter.next();
System.out.println(entry.getKey() + "=>" + entry.getValue());
}
/* Step 2: send the next dummy JSON file */
JSONParser parser = new JSONParser();
JSONObject jsonObject1 = null;
try {
Object obj1 = parser.parse(new FileReader("d:\\JsonStruc1.json"));
jsonObject1 = (JSONObject) obj1;
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
return Response.status(200).entity(jsonObject1).build();
}
The CORS class of my Project is as follows :
public class CorsFilter extends OncePerRequestFilter{
private Properties prop = new Properties();
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
System.out.println("Inside Cross Origin Resource Sharing Filter Class");
System.out.println(request.getContentType());
System.out.println(request.getContentLength());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
filterChain.doFilter(request, response);
}
}
There is no Problem regarding sending Dummy JSON data through the URL (/service/question/dummy/) But
when I am trying to get The JSON data (/service/question/insert/dummy/) and send the next JSON object
through the method setDummyJSON(....) then I am having trouble. The AngularJS (Client) side is showing the following exception message :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at /FetchQuestions/service/question/insert/dummy/. This can be fixed by moving the resource to the same domain or enabling CORS.
On invoking the URL (/service/question/insert/dummy/) from localhost with a JSON String as Content Body the following error message is thrown :
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().
What am I doing Wrong ? Any Help will be appreciated. Thanks.
There is Nothing Wrong with the above code.
For Some Reason Whenever the Content-Type was set to application/json in AngularJS(Client Side) by using the following command :
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json';
The Server Side received a Content-Type of null. Any other Content-Type like application/x-www-form-urlencoded or text/plain Works but the Problem occurs only with application/json (even though AngularJS was sending JSON data to Server Side).
Thus a little change in the Controller class Fixed the Problem.
#RequestMapping(value = "/insert/dummy/",method= RequestMethod.POST")
public Response setDummyJSON(#RequestBody String inputjsonObj){
/* Step1: Receive The Data in Text/Plain Format
Step2: Conver The String To JSON Object. Do Necessary Processing.
Step3: Return Dummy JSON Object through the Response. */
return Response.status(200).entity(jsonObject1).build();
}

Categories