Java代码--简单接口的实现

Eclipse中新建web项目,项目中新建一个servlet接口,servlet中java代码如下:

public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {

	this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		
	request.setCharacterEncoding("UTF-8");
	response.setCharacterEncoding("UTF-8");
	response.setContentType("text/plain;charset=utf-8");
	response.addHeader("Access-Control-Allow-Origin", "*");  //跨域问题
	response.addHeader("Access-Control-Allow-Headers", "*");
	response.addHeader("Access-Control-Allow-Methods","GET,POST,PUT,HEAD,DELETE,OPTIONS");
				
	//1.接收JSON格式参数
	BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
	String line = null;
	StringBuilder sb = new StringBuilder();  //1.读取实体内容封装成字符数组
	while ((line = br.readLine()) != null) {  
		sb.append(line);
	}
	br.close();
	JSONObject jo = JSONObject.fromObject(sb.toString()); //2.将字符数组封装成json对象
	String img1=jo.getString("img1"); //3.读取客户端发过来的json串,组装参数
	String img2=jo.getString("img2");
	System.out.println("------img1:"+img1);  //控制台打印出上传的参数
	System.out.println("------img2:"+img2);
		
		
	//2.直接URL传递参数(接口?img1=123&img2=456)
	/*
	String img1=request.getParameter("img1");
	String img2=request.getParameter("img2"); 
	//向客户端发送数据  
	response.setContentType("text/javascript");  
	PrintWriter out=response.getWriter(); 
	System.out.println("------img1:"+img1);
	System.out.println("------img2:"+img2);
	*/
		
	//3.Map 传递参数(接口?img1=123&img2=456&img3=3...)任意值
	/*
	Map paramMap = request.getParameterMap();
	for(Map.Entry entry:paramMap.entrySet()){
		String key = entry.getKey();
		String[] value = entry.getValue(); 
		System.out.println(key + " : " +  value[0]);
	}
	*/
		
	//4.httpUrlConnection Post请求传参数及 客户端接收参数 
	/*
	InputStreamReader reader=new InputStreamReader(request.getInputStream());  //接收请求参数  
	BufferedReader buffer=new BufferedReader(reader);  
	String data=buffer.readLine();  
	String a[] = data.split(":::");  
	System.out.println(data);  
	String header=request.getHeader("headerdata");  //头部信息  
	System.out.println(header);  
	response.setContentType("text/javascript");  //向客户端发送数据  
	PrintWriter out=response.getWriter();
	String img1=a[0];
	String img2=a[1];
	System.out.println("------img1:"+img1);
	System.out.println("------img2:"+img2);
	*/	
}

将项目部署在Tomcat或其它容器中 (web.xml中***为接口地址),可以用Postman调用接口进行测试。

有什么需要改进和补充的地方希望大家多多提出,共同进步

你可能感兴趣的:(JAVA晋级)