与android客户端以JSON格式进行数据通信

AndroidClient代码:

######################################

package android.test;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;
import yt.tool.Log;


public class AndroidClient {
@Test
public void HttpPostData() throws Exception { 
for(int i = 0;i < 1;i++){
HttpClient httpclient = new DefaultHttpClient();  
 String uri ="http://192.168.1.55:8888/android/AndroidService";
 HttpPost httppost = new HttpPost(uri);   
 //添加http头信息 
         httppost.addHeader("Content-Type", "application/json"); 
         httppost.addHeader("User-Agent", "mozilla/5.0");  
         JSONObject obj = new JSONObject(); 
         obj.put("age", 26); 
         obj.put("name", "nikerlover"); 
         obj.put("password", 45667);
         System.out.println("测试结果:"+obj.toString());
         StringEntity se = new StringEntity(obj.toString());
         httppost.setEntity(se);
         HttpResponse response = httpclient.execute(httppost);  
        //检验状态码,如果成功接收数据 
          int code = response.getStatusLine().getStatusCode();  
          if (code == 200) { 
          System.out.println("######################success####################");
          BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
          String line = null;
          while((line = reader.readLine()) !=null){
          System.out.println(line);
          }
         
          }
}
 
}

public static String readJSONString(InputStream inputStream){
        StringBuffer json = new StringBuffer();
        int line;
        try {
        BufferedInputStream reader = new BufferedInputStream(inputStream);
        System.out.println("测试返回结果内容1");
            while((line = reader.read()) != 0) {
                json.append(line);
            }
            Log.w("返回服务器端结果", "内容:" + json);
            System.out.println("测试返回结果内容2");
            reader.close();
        }
        catch(Exception e) {
            System.out.println(e.toString());
        }
        return json.toString();
    }


}

###############################

AndroidService代码

#############################

package android.test;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import yt.tool.Log;
import net.sf.json.JSONObject;
public class AndroidService extends HttpServlet {
private String Json;
private int age;
private String name;
private String password;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}


@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
String jsonContent = readJSONString(req);
JSONObject obj= JSONObject.fromObject(jsonContent);
AndroidService ase =(AndroidService)JSONObject.toBean(obj, AndroidService.class);
Log.w("年龄数据", "内容:" + ase.getAge());
resp.setContentType("application/json;charset=UTF-8");
Writer out = resp.getWriter();
out.write(jsonContent);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}



}


public String getJson() {
return Json;
}


public void setJson(String json) {
Json = json;
}


public int getAge() {
return age;
}


public void setAge(int age) {
this.age = age;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public String getPassword() {
return password;
}


public void setPassword(String password) {
this.password = password;


public static byte[] readInputStream(InputStream inStream) throws Exception{
       ByteArrayOutputStream outStream = new ByteArrayOutputStream();
       byte[] buffer = new byte[1024];
       int len = 0;
       while( (len = inStream.read(buffer)) !=-1 ){
           outStream.write(buffer, 0, len);
       }
       byte[] data = outStream.toByteArray();//网页的二进制数据
       outStream.close();
       inStream.close();
       return data;
   }
 
public static String readJSONString(HttpServletRequest request){
       StringBuffer json = new StringBuffer();
       String line = null;
       try {
           BufferedReader reader = request.getReader();
           while((line = reader.readLine()) != null) {
               json.append(line);
           }
           Log.w("httpclient测试", "内容:" + json);
       }
       catch(Exception e) {
           System.out.println(e.toString());
       }
       return json.toString();
   }




}

###################################

web.xml中的配置

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">


  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>

 <servlet>
<servlet-name>fetchInfo</servlet-name>
<servlet-class>android.test.AndroidService</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>


<servlet-mapping>
<servlet-name>fetchInfo</servlet-name>
<url-pattern>/android/AndroidService</url-pattern>
</servlet-mapping>
  
</web-app>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值