Issue
I have an AJAX making a POST to a servlet. Servlet does some computation and returns a response. AJAX success function reads the response and does certain things.
AJAX CALL
$.ajax( {
type: "POST",
url: "/bin/path/to/Servlet",
data: $(this).serialize(),
dataType: "html",
success: function(responseValue) {
if(responseValue == '200') {
// Do something
}else {
console.log("it is not 200");
}
},
error: trialForm.trialError
}).done(function(status) {
$(trialForm.submitButton).show();
$(trialForm.loader).hide();
});
}
SERVLET
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
response.setContentType("text/html");
URL url = new URL("www.apriurl.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestProperty("Authorization","XXXXZZZZ " + strSig);
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("ZZZZZ",clientID);
OutputStream os = conn.getOutputStream();
os.write(inputParameters.getBytes());
os.flush();
System.out.println(conn.getResponseCode());
response.getWriter().write(conn.getResponseCode());
}
- responseValue is a variable used in teh java class.
- It has the right value. I see the value being print in log file after sys out executed
- The response is just a garbled question mark (?). I console logged it. I am guessing it has to do something with the data type. I tried a few other types but couldn;t figure out. Any help is appreicated.
Solution
This is doing a write (int)
rather than a write (String)
so if you do write(200)
it is sending the ascii value of 200
try sending 200
as a String
as
response.getWriter().write(String.valueOf (conn.getResponseCode()));
see https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#write(int)
public void write(int c)
Writes a single character.
Answered By - Scary Wombat