json作为客户端调用服务端说明

来源:互联网 发布:编程求圆的周长和面积 编辑:程序博客网 时间:2024/06/05 19:33

在些仅对服务端调用客户端的方法进行说明,服务端的开发相对简单,直接在servlet上调用指定的方法即可,然后通过json方式,对期传过来的参数进行解析.此实例分四个文件,分别如下:需要引用的架包为:jackson-core-2.1.0.jar   jackson-annotations-2.1.0.jar jackson-databind-2.1.0.jar   commons-httpclient-3.1.jar commons-logging-1.0.4.jar  commons-codec-1.3.jar

1、Json 

package yushan.dou.json;
import java.text.ParseException;
import yushan.dou.json.TmsWeatherFromGps.Data;
public class Json {
private static GlobalServletImpl globalServlet = new GlobalServletImpl();
/**
* 1、当作为客户端调用服务端时,使用以下方法就可以,其中连接的地址及参数需要修改
* 2、当作为服务端供别人调用时,用法与servlet用法相似,可用receiveTmsWeatherFromGps方法解析传递过来的值
* */
public static void main(String[] args) {
//客户端
String response = "";
  try{
// data可以通过json直接将参数直接转为一个字符串,对像格式需要与传递数据的格式一一对应
// JsonUtil json=new JsonUtil();
// ComeOnRecordsSearchFromGps gps=new ComeOnRecordsSearchFromGps();
// gps.setOrgnum(ORGNUM);
// String st = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(stdate));
// String et = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
// gps.setStarttime(st);
// gps.setEndtime(et);
// JsonUtil json=JsonUtil.nonEmptyMapper();
// data=json.toJson(gps);
  //传递的json格式的数据
String data="{\"taskid\":\"A01130717008\",\"vehicleno\":\"沪BQ8292\",\"updatetime\":\"2013-07-12 13:20:02\",\"passinfo\":[{\"sitename\":\"十院/药房\",\"siteid\":\"310000002338\",\"siteorder\":\"1\",\"intime\":\"2013-07-12 14:01:13\",\"outtime\":\"2013-07-12 14:11:23\",\"opentime\":\"2013-07-12 14:01:15\",\"closetime\":\"2013-07-12 14:11:55\",\"mileage\":5.25},{\"sitename\":\"市中医/杏林310000002611\",\"siteid\":\"310000002611\",\"siteorder\":\"2\",\"intime\":\"2013-07-12 14:20:47\",\"outtime\":null,\"opentime\":\"2013-07-12 14:21:57\",\"closetime\":\"2013-07-12 14:22:19\",\"mileage\":7.92}]}";
//连接并得到返回值
response=globalServlet.sendGpsMessage(data);
System.out.println(response);
//解析返回报文,当返回格式与TmsWeatherFromGps对应的,可调用此方法
// receiveTmsWeatherFromGps(response);
  }catch(Exception e){
  e.printStackTrace();
  }
}

//此方法是对返回格式是json的数据进行指定格式的解析
public static void receiveTmsWeatherFromGps(String data) throws ParseException{
  JsonUtil json=new JsonUtil();
  TmsWeatherFromGps gps=json.fromJson(data, TmsWeatherFromGps.class);
  Data[] d=gps.getData();
  for(int i=0;i<d.length;i++){
  System.out.println(d[i].getCity());
  System.out.println(d[i].getDayweather());
  }
  }
}


2、GlobalServletImpl

package yushan.dou.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
public class GlobalServletImpl {
public static final String REQUEST_CHARSET = "UTF-8";
public static final String RESPONSE_CHARSET = "UTF-8";
protected String HTTP_URL = "http://127.0.0.1:8199/gytms/servlet/globalServlet";

/**
* @param method
*            具体API接口的名称
* @param gps_key
*            密钥
* @param data
*            JSON格式的字符串
* @return           
*/
public String sendGpsMessage(String data) {
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();
client.setTimeout(30000);
PostMethod postMethod = new PostMethod(HTTP_URL);
//设置参数,此json接口包括method,gps_key,data的三个参数
postMethod.setParameter("method", "receiveShipmentPlanFromGps");
postMethod.setParameter("gps_key", "HTGPS");
        postMethod.setParameter("data", data);

//编码设置
postMethod.getParams().setHttpElementCharset(REQUEST_CHARSET);
postMethod.getParams().setContentCharset(REQUEST_CHARSET);

try {
client.executeMethod(postMethod);
//获取返回信息n
if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(postMethod.getResponseBodyAsStream(),
RESPONSE_CHARSET));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
}
} catch (IOException e) {
System.out.println("执行HTTP Post请求" + HTTP_URL + "时,发生异常!");
} finally {
postMethod.releaseConnection();
}
return response.toString();
}
}


3、JsonUtil


package yushan.dou.json;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

@SuppressWarnings("unchecked")
public class JsonUtil {
private ObjectMapper mapper;
public JsonUtil() {
this(null);
}

public JsonUtil(Include include) {
mapper = new ObjectMapper();
//设置输出时包含属性的风格
if (include != null) {
mapper.setSerializationInclusion(include);
}
//设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
/**
* 反序列化POJO或简单Collection如List<String>.

* 如果JSON字符串为Null或"null"字符串, 返回Null.
* 如果JSON字符串为"[]", 返回空集合.

* 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String,JavaType)
* @see #fromJson(String, JavaType)
*/
public <T> T fromJson(String jsonString, Class<T> clazz) {
if (jsonString == null || jsonString.equals("")) {
return null;
}
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
return null;
}
}


public static JsonUtil nonEmptyMapper() {
return new JsonUtil(Include.NON_EMPTY);
}
}


4、TmsWeatherFromGps

package yushan.dou.json;


public class TmsWeatherFromGps {
private String code;

private String message;

private Data[] data;

public static class Data{
/**
* 城市名称
*/
private String city;

/**
* 预报日期
*/
private String reportdate;

/**
* 白天天气
*/
private String dayweather;

/**
* 白天温度
*/
private String daytempra;

/**
* 白天风向
*/
private String daywinddirec;

/**
* 白天风力
*/
private String daywindlevel;

/**
* 夜间天气
*/
private String nightweather;

/**
* 夜间温度
*/
private String nighttempra;

/**
* 夜间风向
*/
private String nightwinddirec;

/**
* 夜间风力
*/
private String nightwindlevel;

/**
* 更新时间
*/
private String remark1;

/**
* 备用
*/
private String remark2;

/**
* 备用
*/
private String remark3;

/**
* 备用
*/
private String remark4;

/**
* 备用
*/
private String remark5;

/**
* 创建时间(调用接口时间)
*/
private String createdate;


public String getCity() {
return city;
}


public void setCity(String city) {
this.city = city;
}



public String getDayweather() {
return dayweather;
}
public void setDayweather(String dayweather) {
this.dayweather = dayweather;
}
public String getDaytempra() {
return daytempra;
}
public void setDaytempra(String daytempra) {
this.daytempra = daytempra;
}
public String getDaywinddirec() {
return daywinddirec;
}
public void setDaywinddirec(String daywinddirec) {
this.daywinddirec = daywinddirec;
}
public String getDaywindlevel() {
return daywindlevel;
}
public void setDaywindlevel(String daywindlevel) {
this.daywindlevel = daywindlevel;
}
public String getNightweather() {
return nightweather;
}
public void setNightweather(String nightweather) {
this.nightweather = nightweather;
}
public String getNighttempra() {
return nighttempra;
}
public void setNighttempra(String nighttempra) {
this.nighttempra = nighttempra;
}
public String getNightwinddirec() {
return nightwinddirec;
}
public void setNightwinddirec(String nightwinddirec) {
this.nightwinddirec = nightwinddirec;
}
public String getNightwindlevel() {
return nightwindlevel;
}
public void setNightwindlevel(String nightwindlevel) {
this.nightwindlevel = nightwindlevel;
}
public String getRemark2() {
return remark2;
}
public void setRemark2(String remark2) {
this.remark2 = remark2;
}
public String getRemark3() {
return remark3;
}
public void setRemark3(String remark3) {
this.remark3 = remark3;
}
public String getRemark4() {
return remark4;
}
public void setRemark4(String remark4) {
this.remark4 = remark4;
}
public String getRemark5() {
return remark5;
}
public void setRemark5(String remark5) {
this.remark5 = remark5;
}
public String getReportdate() {
return reportdate;
}
public void setReportdate(String reportdate) {
this.reportdate = reportdate;
}
public String getRemark1() {
return remark1;
}
public void setRemark1(String remark1) {
this.remark1 = remark1;
}
public String getCreatedate() {
return createdate;
}
public void setCreatedate(String createdate) {
this.createdate = createdate;
}
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data[] getData() {
return data;
}
public void setData(Data[] data) {
this.data = data;
}
}

原创粉丝点击