苍穹
管理员
管理员
  • UID2
  • 粉丝0
  • 关注0
  • 发帖数202
阅读:8824回复:1

关于Ajax call get and post method, 和前端解决跨域

楼主#
更多 发布于:2018-08-25 21:49
关于Ajax call的一些介绍:
1.get
var urlAJAXServlet = "";
jQuery.support.cors = true;
$.ajax({
url: urlAJAXServlet,
type: 'GET',
crossDomain: true,
dataType: 'json',
async: false,
beforeSend: function(xhr){
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success : function(data) {
responseJson=data;
console.log("Success: in call json service..."+JSON.stringify(responseJson));
},
error:function(XMLHttpRequest, textStatus, errorThrown){
console.log("Error: in call json service...");
console.log("Error: in call json service..."+XMLHttpRequest);
console.log("Error: in call json service..."+textStatus);
console.log("Error: in call json service..."+errorThrown);
}
})
 
2. POST
var requestForHost={};
var urlAJAXServlet = "";
jQuery.support.cors = true;
$.ajax({
contentType:"application/json",
url: urlAJAXServlet,
type: 'POST',
crossDomain: true,
data: JSON.stringify(requestForHost),
dataType: 'json',
async: false,
beforeSend: function(xhr){
xhr.setRequestHeader('channelId', 'MEM');
xhr.setRequestHeader('countryCode', 'SG');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success : function(data) {
reponseGDTJson=data;
console.log("Success: in call json service..."+JSON.stringify(reponseGDTJson));
},
error:function(XMLHttpRequest, textStatus, errorThrown){

console.log("Error: in call json service...");
console.log("Error: in call json service..."+XMLHttpRequest);
console.log("Error: in call json service..."+textStatus);
console.log("Error: in call json service..."+errorThrown);
}
});
这样的方法也许call 本地的api没有问题,但是一旦上到环境上,我们就会面临跨域问题,解决方法
这样的我们可以在本地创建一个servlet,虽然这样有点麻烦但是还是很好用的,现在这个就是纯Jquery
Ajax call, 当然你可以用SpringMVC 和Backbonds的框架来call 但是可能也会有跨域问题。这个还没有研究,
现在先说纯Jquery建立一个servlet来解决前台的跨域问题。
我们可以在本地创建一个servlet,用的是httpClients
public class SBGetDatesServlet extends HttpServlet{
private static final long serialVersionUID=1L;
public SBGetDatesServlet(){
super();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
doPost(request,response);

}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
CloseableHttpResponse httpResponse = null;
try {
httpClient = HttpClients.createDefault();
//Start read the json String that ajax call Post Passed
BufferedReader br1 = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
String line = null;
StringBuilder sb= new StringBuilder();
while((line = br1.readLine())!=null){
sb.append(line);
}
//END
JSONObject json = JSONObject.fromObject(sb.toString());//Json String - > Json object
httpPost = new HttpPost("https://......"); // Rest server URL
StringEntity input = new StringEntity(json.toString());
input.setContentType("application/json"); // Json format
httpPost.setEntity(input);
httpPost.addHeader("channelId", request.getHeader("channelId"));
httpPost.addHeader("countryCode", request.getHeader("countryCode"));
httpPost.addHeader("Content-Type", "application/json");


httpResponse = httpClient.execute(httpPost);

if (httpResponse.getStatusLine().getStatusCode() != 200) {

throw new RuntimeException("Failed : HTTP error code : " + httpResponse.getStatusLine().getStatusCode()); // Error
}
BufferedReader br = new BufferedReader(new InputStreamReader((httpResponse.getEntity().getContent())));
String responseOut = "";
String output;
// System.out.println("Output from Server .... \n");// Console log
while ((output = br.readLine()) != null) { // get output
System.out.println(output);
responseOut += output;
}
Map<String, String> OutputMap = new HashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
Writer out = response.getWriter();
try {
OutputMap = mapper.readValue(responseOut, new TypeReference<HashMap<String, Object>>() {
});
System.out.println(OutputMap);
JSONObject jsonReponse = new JSONObject();
jsonReponse.putAll(OutputMap);
// System.out.println(jsonReponse.putAll(responseOut));
// out.write(jsonReponse.toString());
MemfisLogger.logMessage(MemfisLogger.DEBUG, "", "Json response " + responseOut);
out.write(responseOut);//我们可以用out.write将正确的json response返回到页面上。
out.flush();
// System.out.println(OutMap); // console log
} catch (Exception e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpResponse.close();
httpClient.close(); // close ALL
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
苍穹
管理员
管理员
  • UID2
  • 粉丝0
  • 关注0
  • 发帖数202
沙发#
发布于:2018-08-25 21:50
我们还有一种方法,同样是新建一个servlet但是我们不是用httpClients, 而是用
restAccessor,但是这个需要一些版本比较高的Jar包,
httpclient-4.5.2.jar
httpcore-4.4.5.jar
spring-beans-4.2.3.RELEASE.jar
spring-core-4.2.3.RELEASE.jar
spring-web-4.2.3.RELEASE.jar
jackson-all-1.9.9.jar
jackson-annotations-2.7.3.jar
jackson-core-2.7.3.jar
jackson-databind-2.7.3.jar

 
 
public class SBGetDatesServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private static final String HOST_NAME;
private static final String PORT;
private static final String PROTOCOL;

static {
String url =

String[] sourceStrArray = url.split(":");
int length = sourceStrArray[1].length();
String hostName = sourceStrArray[1].substring(2,length);
HOST_NAME=hostName;
PORT=sourceStrArray[2];
PROTOCOL=sourceStrArray[0];
}
public SBGetDatesServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ObjectMapper mapper = new ObjectMapper();

RestAccessor restAccessor=new RestAccessor();
restAccessor.setHost(HOST_NAME);
restAccessor.setPort(PORT);
restAccessor.setProtocol(PROTOCOL);
restAccessor.setPath("");
RestRequestObject req=new RestRequestObject();
try
{
BufferedReader br1 = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
String line = null;
StringBuilder sb= new StringBuilder();
while((line = br1.readLine())!=null){
sb.append(line);
}

JSONObject json = JSONObject.fromObject(sb.toString());

System.out.println("SBGetDatesServlet : doPost() : Json Object Request" + json);
req.setHttpMethod(HttpMethod.POST);
req.setHttpRequestHeaders(getDefaultHTTPRequestHeaders());
req.setRequestBody(sb.toString());
RestResponseObject res = restAccessor.makeRESTCall(req);
System.out.println("calling makeRESTCall completed " + mapper.writeValueAsString(res));

res.getResponseBody();
JSONObject jsonRes = JSONObject.fromObject(res.getResponseBody().toString());

System.out.println("SBGetDatesServlet : doPost() : Json Object Response" + jsonRes);
Writer out = response.getWriter();
out.write(res.getResponseBody().toString());
out.flush();
if (res.isSuccess())
{
System.out.println("invokeCustUpdRESTService Success ");
resCode = "0";
}
else
{
resCode = "-1";
System.out.println("invokeCustUpdRESTService Failed ");
if (res.getErrorResponse() != null) {
System.out.println("invokeCustUpdRESTService Failed :: " + res.getErrorResponse());
} else {
System.out.println("invokeCustUpdRESTService Failed - NO ESB UUID :: ");
}
}
}
catch (Exception e)
{
resCode = "-1";
System.out.println("invokeCustUpdRESTService || invokeCustUpdRESTService || Exception: " + e);
}
}
private static HttpHeaders getDefaultHTTPRequestHeaders()
{
String methodName = "getDefaultHTTPRequestHeaders";
HttpHeaders requestHeaders = new HttpHeaders();
try {

requestHeaders.add("countryCode", "SG");
requestHeaders.add("channelID", "MEM");

}
catch (Exception e)
{
System.out.println("RESTfulServiceInvoker"+ "getDefaultHTTPRequestHeaders"+ "Exception" +e);
}
System.out.println("RESTfulServiceInvoker"+ "getDefaultHTTPRequestHeaders"+ "requestHeaders" +requestHeaders);
return requestHeaders;
}
}
 
但是如果真正解决跨域问题还是需要后台的API端相配合的。
游客


返回顶部