I am calling an url using ajax - but when it is called I am getting response HTTP/1.1 403
below is my calling code
function callApi() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "http://103.240.91.110/GENCLASS/checkApi.do?
$95599&99&3456790&09012020152103*", true);
xmlhttp.send();
}
Below is the server side method who is sending the response
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward(); // return value
ApiForm apiForm = (ApiForm)form;
try {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");
// send back response
System.out.println("true");
}catch(Exception e){
errors.add(ActionErrors.GLOBAL_ERROR, new org.apache.struts.action.ActionError("load.error.unknown"));
//log.error("Critical Error " + e);
}
if (!errors.isEmpty()) {
saveErrors(request, errors);
forward = mapping.findForward("failure");
} else {
forward = mapping.findForward("success");
}
return (forward);
}
Whenever I am calling the URL I am getting response HTTP/1.1 403
Note that It is working perfectly when I am requesting through browser
I am using tomcat 8.5 on windows on server (called resource)
Any assistance will be appreciated
Related
The following method is intended to accept an Http method and url, execute the method against the url, and return the resulting response to the caller. It returns ActionResult because there are error conditions that need to be handled.
At present, the method only tells the caller whether the call succeeded or not, it doesn't return details about the response from the downstream server. I would like the caller to receive the entire response (including status code, response body, etc) from the call.
How can I convert the HttpResponseMessage to something appropriate to return via ActionResult?
[HttpGet(#"{method}")]
public async Task<IActionResult> RelayRequest(string method, [FromQuery] string url)
{
var httpMethod = new HttpMethod(method);
Uri uri;
try
{
uri = new Uri(url);
}
catch (Exception e)
{
return BadRequest("Bad URL supplied: " + e.Message);
}
var request = new HttpRequestMessage(httpMethod, uri);
try
{
var response = await _httpClient.SendAsync(request);
// WANT TO RETURN (ActionResult)response HERE! <<<<<<<<<<
if (response.IsSuccessStatusCode)
{
return Ok();
}
return BadRequest(response);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
It's going to depend a little bit on the response you're receiving from your await _httpClient.SendAsync(request) but you could deserialize the response Content from the request and return that from your controller.
For example, if the request used JSON, you could do the following:
if (response.IsSuccessStatusCode)
{
// Assuming the use of Newtonsoft.Json
var responseBody = JsonConvert.DeserializeObject<RequestResponse>(await response.Content.ReadyAsStringAsync());
return Ok(responseBody);
}
I have 2 Web API controllers:
1. Runtime1Controller
2. Runtime2Controller
In Runtime2Controller:
public HttpResponseMessage PostCreateRequest(KeyRequest keyRequest)
{
try
{
Runtime1Controller runtime1Controller = new Runtime1Controller();
HttpResponseMessage response = runtime1Controller.PostCreateRequest(keyRequest);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
catch(Exception ex)
{
throw;
}
}
In Runtime1Controller, I return HttpResponse message:
public HttpResponseMessage PostCreateRequest(KeyRequest keyRequest)
{
// Process Data .....
Request.CreateResponse(HttpStatusCode.Created, keyRequest);
}
Then, why All the time Request is NULL. If I directly call Runtime1Controller PostCreateRequest, it is not NULL. Why SO???
in Runtime1Controller, use return when you create the response (or maybe you dont put this part):
public HttpResponseMessage PostCreateRequest(KeyRequest keyRequest)
{
// Process Data .....
return Request.CreateResponse(HttpStatusCode.Created, keyRequest);
}
Here in the below code i want to call a servlet through ajax and then i redirect the data from servlet to jsp.ajax call to servlet is working fine but the problem is redirecting to the jsp page is not displayed in the browser and the same jsp page is displayed when i used with javascript code without ajax.
javascript ajax code in the jspfile:
function generate(){
...
...
var url="RedirectServlet";
var ajax=new AJAXInteraction(url,"RedirectServlet");
var param ="FD="+FD+"&TD="+TD+"&actionid="+status+"&usercode="+usercode+"&action=reports"+"";
ajax.send(param);
....
}
function AJAXInteraction(url, actionType) {
this.url = url;
var req = init();
var actionRequested = actionType;
req.onreadystatechange = processRequest;
function init() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest () {
if (req.readyState == 4) {
if (req.status == 200) {
if(actionRequested=="TestDelegation") {
PostProcess1(req.responseXML);
}
}
}
}
this.send = function(param) {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(param);
}
}//end of AJAX Interaction object.
Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
System.out.println("calling doPost() ");
response.setContentType("text/html;charset=WINDOWS-1256");
String action=request.getParameter("action");
System.out.println(action);
if(action.equals("reports")){
System.out.println("inside reports");
//Getting values from Reports_arb.jsp
String Fromdate=request.getParameter("FD");
String Todate=request.getParameter("TD");
String status=request.getParameter("actionid");
String usercode=request.getParameter("usercode");
//placing given values in a session
request.setAttribute("FD", Fromdate);
request.setAttribute("TD", Todate);
request.setAttribute("actionid", status);
request.setAttribute("usercode", usercode);
//Redirecting to showReport_arb.jsp
//response.sendRedirect("showReport_arb.jsp");
ServletContext sc = getServletContext();
sc.getRequestDispatcher("/sample.jsp").forward(request, response);
You need to understand the fact that when you send http request from ajax, it means that you are sending the request in separate thread and not in the main thread (the page itself from where you are sending the request). So redirection at the servlet will not reflect at the client end. In order to achieve this, send back the URL to which you want to redirect as a response to request and on success method of ajax simply use java script window.location(URL);
At servlet
JSONObject jobj = new JSONObject()
String urlToRedirect = "test.jsp";
jobj.put("url",urlStr);
response.getWriter().write(jobj.toString());
At client end
$.ajax({
url: 'servletName',
data: {
userID: selectedID
},
type: 'post',
success: function(data){
window.location = data.url;
}
});
Instead of creating the request and response object, use jquery Ajax. It is very simple to use.
/* Send the data using post and put the results in a div */
$.ajax({
url: "/YourServlet",
type: "post",
data: values,
success: function(){
alert("success");
$("#result").html('submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
I've tried to put an object in a session inside a servlet and read it inside a javascript code. Actually that works, but after converting the normal javascript code to AJAX, it couldn't recognize it any more.
This is the servlet's code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject object = new JSONObject();
object.put("A","A");
request.getSession().setAttribute("json", object.toJSONString());
}
And I want to recieve it in the following AJAX code.
<script type="text/javascript">
function runAjax(){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var json = <%=session.getAttribute("json")%>
alert(json);
}
}
ajax.open("GET", "servlet", true);
ajax.send();
}
</script>
json content is null.
Any help please?
Thanks very much.
JavaScript executes in the browser. JSP scriptlet executes on the server.
So when you make a request to the page containing the above JavaScript code, the HTML is generated by the server. The server executes the following scriptlet code: <%=session.getAttribute("json")%>. Since, at this moment, the session attribute doesn't exist, the generated HTML is:
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var json = null
alert(json);
}
}
Then this HTML/JS code is downloaded by the browser, and the JS code is executed in the browser. The browser sends an AJAX request to the server, and when the response comes back, the browser executes the following function:
function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var json = null
alert(json);
}
}
So obviously, what is displayed in the allert box is null.
You can try like this to have the session object value in javascript.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject object = new JSONObject();
object.put("A","A");
request.getSession().setAttribute("json", object.toJSONString());
PrintWriter out=response.getWriter();
out.write(object.toJSONString());
}
<script type="text/javascript">
function runAjax(){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var json = ajax.responseText;
alert(json);
}
}
ajax.open("GET", "servlet", true);
ajax.send();
}
</script>
i hava created the ajax XMLHttpRequest request for getting the data dyanmically ,
here is the code
var XMLHttpReq;
function createXMLHttpRequest() {
if (window.XMLHttpRequest) {
XMLHttpReq = new XMLHttpRequest();
} else {
if (window.ActiveXObject) {
try {
if(XMLHttpReq==null)
XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
if(XMLHttpReq==null)
XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
}
}
this is the method which sends the request
function personList(person) {
createXMLHttpRequest();
var url="query?option=person&userName="+person.innerHTML;
XMLHttpReq.open("GET", url, true);
XMLHttpReq.onreadystatechange =personListResponse;
XMLHttpReq.send(null);
}
function personListResponse() {
if (XMLHttpReq.readyState == 4) {
if (XMLHttpReq.status == 200) {
var xml=XMLHttpReq.responseXML;
}
}
}
the request is sent to the servlet only for the first time,when i try for the second the request is not sent ,instead am getting the previous response what i got earlier
I suppose it's cache.
Try adding this before the request:
XMLHttpReq.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
XMLHttpReq.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
XMLHttpReq.setRequestHeader("Pragma", "no-cache");
If it doesn't work, try adding an additional parameter to your url, making it unique and therefore, not caching.
var url="query?option=person&userName="+person.innerHTML + "&d=" + new Date().getTime()
I really don't like this solution, but it helps you to know if the problem is related to cache.