android 发送接收JSON

  1. package com.yqq.jsonclienttest;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.OutputStream;  
  5. import java.net.InetAddress;  
  6. import java.net.Socket;  
  7. import java.net.UnknownHostException;  
  8.   
  9. import org.json.JSONException;  
  10. import org.json.JSONObject;  
  11.   
  12. import android.app.Activity;  
  13. import android.os.Bundle;  
  14. import android.text.TextUtils;  
  15. import android.util.Log;  
  16. import android.view.View;  
  17. import android.widget.EditText;  
  18. import android.widget.Toast;  
  19.   
  20.   
  21.   
  22. /** 
  23.  * 套接字客户端, 
  24.  * 1、先生成JSON对象 
  25.  * 2、将JSON对象转成JSON字符串 
  26.  * 3、将JSON字符串转成字节数组写入套接字输出流 
  27.  * @author yqq_coder 
  28.  * 
  29.  */  
  30. public class MainActivity extends Activity {  
  31.     private EditText et_name;  
  32.     private EditText et_age;  
  33.     private EditText et_sex;  
  34.     private String host="172.21.133.15";//同一个局域网内作为服务端的手机的IP,使用端口8155  
  35.   
  36.     @Override  
  37.     protected void onCreate(Bundle savedInstanceState) {  
  38.         super.onCreate(savedInstanceState);  
  39.         setContentView(R.layout.activity_main);  
  40.         et_name=(EditText) findViewById(R.id.et_name);  
  41.         et_age=(EditText) findViewById(R.id.et_age);  
  42.         et_sex=(EditText) findViewById(R.id.et_sex);  
  43.     }  
  44.       
  45.       
  46.     public void submit(View v) throws JSONException{  
  47.         if(TextUtils.isEmpty(et_name.getText().toString().trim())||TextUtils.isEmpty(et_age.getText().toString().trim())||TextUtils.isEmpty(et_sex.getText().toString().trim())){  
  48.             Toast.makeText(MainActivity.this"信息不能为空!!!"0).show();  
  49.             return;  
  50.         }  
  51.         JSONObject jsonObject=new JSONObject();  
  52.         jsonObject.put("name", et_name.getText().toString().trim());  
  53.         jsonObject.put("age", et_age.getText().toString().trim());  
  54.         jsonObject.put("sex", et_sex.getText().toString().trim());  
  55.         final String  result=jsonObject.toString();  
  56.         Log.i("jSON字符串", result);  
  57.         new Thread(new  Runnable() {  
  58.             @Override  
  59.             public void run() {  
  60.                   
  61.                 try {  
  62.                     Socket socket=new Socket(InetAddress.getByName(host), 8155);  
  63.                     OutputStream os=socket.getOutputStream();  
  64.                     os.write(result.getBytes());  
  65.                     os.flush();  
  66.                     //防止服务端read方法读阻塞  
  67.                     socket.shutdownOutput();  
  68.                 } catch (UnknownHostException e) {  
  69.                     // TODO Auto-generated catch block  
  70.                     e.printStackTrace();  
  71.                 } catch (IOException e) {  
  72.                     // TODO Auto-generated catch block  
  73.                     e.printStackTrace();  
  74.                 }  
  75.                   
  76.             }  
  77.         }).start();  
  78.     }  
  79.   
  80.       
  81.   
  82. }  

服务端代码:

[java]  view plain  copy
  1. package com.yqq.jsonclienttest1;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.net.InetAddress;  
  8. import java.net.ServerSocket;  
  9. import java.net.Socket;  
  10. import java.net.UnknownHostException;  
  11.   
  12. import org.json.JSONException;  
  13. import org.json.JSONObject;  
  14.   
  15. import com.yqq.jsonclienttest1.R;  
  16.   
  17. import android.app.Activity;  
  18. import android.os.Bundle;  
  19. import android.os.Handler;  
  20. import android.os.Looper;  
  21. import android.os.Message;  
  22. import android.text.TextUtils;  
  23. import android.util.Log;  
  24. import android.view.View;  
  25. import android.widget.Button;  
  26. import android.widget.EditText;  
  27. import android.widget.Toast;  
  28.   
  29.   
  30.   
  31. /** 
  32.  * 套接字服务端 
  33.  * @author yqq_coder 
  34.  * 
  35.  */  
  36. public class MainActivity extends Activity {  
  37.     private Button btn;  
  38.       volatile Socket   mSocket;  
  39.       ServerSocket server;  
  40.     private Handler mHandler=new Handler(){  
  41.   
  42.         @Override  
  43.         public void handleMessage(Message msg) {  
  44.             // TODO Auto-generated method stub  
  45.             super.handleMessage(msg);  
  46.             if(msg.what==0x01){  
  47.                 Toast.makeText(MainActivity.this,(String) msg.obj, 500).show();  
  48.                 btn.setEnabled(true);  
  49.             }  
  50.             if(msg.what==0x02){  
  51.                 new Thread(new  Runnable() {  
  52.                     @Override  
  53.                     public void run() {  
  54.                           
  55.                         try {  
  56.                              Log.i("客户端连接""读取客户端发来的数据");  
  57.                             InputStream ins=mSocket.getInputStream();  
  58.                             ByteArrayOutputStream os=new ByteArrayOutputStream();  
  59.                             int len=0;  
  60.                             byte[] buffer=new byte[1024];  
  61.                             while((len=ins.read(buffer))!=-1){  
  62.                                 os.write(buffer);  
  63.                             }  
  64.                             //第一步,生成Json字符串格式的JSON对象  
  65.                             JSONObject jsonObject=new JSONObject(os.toString());  
  66.                             //第二步,从JSON对象中取值如果JSON 对象较多,可以用json数组  
  67.                             String name="姓名:"+jsonObject.getString("name");  
  68.                             String age="年龄:"+jsonObject.getString("age");  
  69.                             String sex="性别:"+jsonObject.getString("sex");  
  70.                             StringBuffer sb=new StringBuffer();  
  71.                             sb.append(name);  
  72.                             sb.append(age);  
  73.                             sb.append(sex);  
  74.                             Looper.prepare();  
  75.                             Message message=Message.obtain();  
  76.                             message.what=0X01;  
  77.                             message.obj=sb.toString();  
  78.                             mHandler.sendMessage(message);  
  79.                             Looper.loop();  
  80.                               
  81.                               
  82.                         } catch (Exception e) {  
  83.                             // TODO Auto-generated catch block  
  84.                             e.printStackTrace();  
  85.                         }finally{  
  86.                               
  87.                             if(mSocket!=null){  
  88.                                 try {  
  89.                                     mSocket.close();  
  90.                                     mSocket=null;  
  91.                                 } catch (IOException e) {  
  92.                                     // TODO Auto-generated catch block  
  93.                                     e.printStackTrace();  
  94.                                 }  
  95.                                   
  96.                             }  
  97.                         }  
  98.                           
  99.                     }  
  100.                 }).start();  
  101.             }  
  102.               
  103.         }  
  104.           
  105.           
  106.     };  
  107.     @Override  
  108.     protected void onCreate(Bundle savedInstanceState) {  
  109.         super.onCreate(savedInstanceState);  
  110.         setContentView(R.layout.activity_main);  
  111.         btn=(Button) findViewById(R.id.btn);  
  112.           
  113.     }  
  114.       
  115.       
  116.       
  117.     public void submit(View v) throws JSONException, IOException{  
  118.         btn.setEnabled(false);  
  119.           
  120.            
  121.           
  122.         new Thread(new  Runnable() {  
  123.               
  124.             @Override  
  125.             public void run() {  
  126.                   
  127.                     try {  
  128.                          Log.i("阻塞,等待客户端连接""<<<<<<<<<");  
  129.                          if(server==null){  
  130.                          server=new ServerSocket(8155);  
  131.                          }  
  132.                          mSocket=server.accept();  
  133.                          Log.i("客户端连接成功""<<<<<<<<<客户端连接成功");  
  134.                         Looper.prepare();  
  135.                         Message message=Message.obtain();  
  136.                         message.what=0X02;  
  137.                         mHandler.sendMessage(message);  
  138.                         Looper.loop();  
  139.                           
  140.                           
  141.                     } catch (Exception e) {  
  142.                         // TODO Auto-generated catch block  
  143.                         e.printStackTrace();  
  144.                     }   
  145.                   
  146.                   
  147.                   
  148.             }  
  149.         }).start();  
  150.     }  
  151.   
  152.       
  153.   
  154. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Android中的HttpClient或者Volley库来实现POST请求并接收返回的JSON信息。 1. 使用HttpClient HttpClient已经过时,但是仍然可以使用。以下是一个示例代码: ``` try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // 设置请求头 httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("Accept", "application/json"); // 构造JSON数据 JSONObject jsonObject = new JSONObject(); jsonObject.put("key1", "value1"); jsonObject.put("key2", "value2"); StringEntity stringEntity = new StringEntity(jsonObject.toString()); // 设置请求体 httpPost.setEntity(stringEntity); // 发送请求 HttpResponse httpResponse = httpClient.execute(httpPost); // 获取返回的JSON信息 BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); StringBuffer stringBuffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { stringBuffer.append(line); } // 处理返回的JSON信息 String response = stringBuffer.toString(); JSONObject responseJson = new JSONObject(response); } catch (Exception e) { e.printStackTrace(); } ``` 2. 使用Volley Volley是一个网络请求库,可以更轻松地发送网络请求。以下是一个示例代码: ``` try { RequestQueue requestQueue = Volley.newRequestQueue(context); String url = "http://example.com/api"; JSONObject jsonBody = new JSONObject(); jsonBody.put("key1", "value1"); jsonBody.put("key2", "value2"); final String requestBody = jsonBody.toString(); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // 处理返回的JSON信息 } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }) { @Override public String getBodyContentType() { return "application/json; charset=utf-8"; } @Override public byte[] getBody() { try { return requestBody == null ? null : requestBody.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } }; requestQueue.add(jsonObjectRequest); } catch (JSONException e) { e.printStackTrace(); } ``` 以上代码仅供参考,具体实现可能需要根据具体情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值