http 发送json到服务器,服务器处理之后返回结果

1.jar包如下:

commons-beanutils.jar
commons-codec-1.3.jar
commons-collections-3.2.jar
commons-httpclient-3.1.jar
commons-lang-2.1.jar
commons-logging-1.0.4.jar
ezmorph-1.0.6.jar
json-lib-2.3-jdk15.jar

2.新建客户端java 工程,新建HttpJsonDemo类,如下:

package com.sk.http.json;

import java.io.IOException;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sk.model.User;

public class HttpJsonDemo {
	private static final Log log = LogFactory.getLog(HttpJsonDemo.class);
	public static String postHttp(String param1, String url) {
		String responseMsg = "";

		// 1.构造HttpClient的实例
		HttpClient httpClient = new HttpClient();

		httpClient.getParams().setContentCharset("utf-8");

		// 2.构造PostMethod的实例
		log.info("[请求地址:"+url+"]");
		PostMethod postMethod = new PostMethod(url);

		postMethod.addParameter("parameters", param1);

		try {
			// 4.执行postMethod,调用http接口
			httpClient.executeMethod(postMethod);// 200

			// 5.读取内容
			responseMsg = postMethod.getResponseBodyAsString().trim();
			JSONObject jsonObjRes = JSONObject.fromObject(responseMsg);
			System.out.println(jsonObjRes);
			System.out.println(jsonObjRes.getString("id"));
			// 6.处理返回的内容
			
		} catch (HttpException e) {
			log.info("----登录出错!----");
		} catch (IOException e) {
			log.info("----登录出错!----");
		} finally {
			// 7.释放连接
			postMethod.releaseConnection();
		}
		return responseMsg;
	}
	public static void main(String[] args) {
		User user = new User();
		user.setName("sk");
		user.setPwd("111111");
	    JSONObject jsonObj = JSONObject.fromObject(user);
		//设置参数和url
		postHttp(jsonObj.toString(), "http://localhost:8080/HttpServerTest/jsonServlet");
	}
}

3.新建服务端web 工程,新建JsonServlet类,如下:

package com;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public class JsonServlet extends HttpServlet {
	 /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)  
	            throws ServletException, IOException {  
	        response.setCharacterEncoding("utf-8");  //设置HTTP 响应的编码
	        PrintWriter out = response.getWriter();  
	        String param1 = request.getParameter("parameters");  
	        JSONObject jsonObj = JSONObject.fromObject(param1);
	        String name = jsonObj.getString("name");
	        String pwd = jsonObj.getString("pwd");
	        if("sk".equals(name) && "111111".equals(pwd)){
	        	Student stu = new Student(1, "张三", "666666");
	        	JSONObject jsonObjOut = JSONObject.fromObject(stu);
	        	out.println(jsonObjOut.toString());
	        	//可以进行业务处理之后返回 TODO
	        }else{
	        	 out.println("参数param1不能为空"); 
	        }
	        out.close();  
	    }  
	  
	    public void doPost(HttpServletRequest request, HttpServletResponse response)  
	            throws ServletException, IOException {  
	        this.doGet(request, response);  
	    }  
}

4.新建Student类,内容如下:

package com;

public class Student {
	private int id;
	private String name;
	private String pwd;
	public Student() {
		
	}
	public Student(int id, String name, String pwd) {
		this.id = id;
		this.name = name;
		this.pwd = pwd;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
}

5.web.xml中配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>HttpServerTest</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<!-- 发送xml的配置 -->
	<servlet>
		<servlet-name>GenXmlServlet</servlet-name>
		<servlet-class>com.GenXmlServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>GenXmlServlet</servlet-name>
		<url-pattern>/GenXmlServlet</url-pattern>
	</servlet-mapping>
	<!-- 发送json的配置 -->
	<servlet>
		<servlet-name>jsonServlet</servlet-name>
		<servlet-class>com.JsonServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>jsonServlet</servlet-name>
		<url-pattern>/jsonServlet</url-pattern>
	</servlet-mapping>
</web-app>

6.运行客户端,控制台打印如下:

 

爱生活,爱分享,爱康宝!

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页