Android笔记:向服务器提交JSON格式的数据

android向服务器提交JSON格式的数据,还可以用于登陆数据提交

new Thread()
 {


 @Override
 public void run() {
 // TODO Auto-generated method stub
 Looper.prepare(); 
 final String urlPath="http://60.176.36.125:8080/wms/resisteruser.do";
 URL url;
 try 
 {
 url = new URL(urlPath);
 /*封装子对象*/
 JSONObject ClientKey = new JSONObject();
 ClientKey.put("appusername", userName.getText().toString());
 ClientKey.put("passwd", passWord.getText().toString());
 ClientKey.put("eigenvalues", eigenValues.getText().toString());
 ClientKey.put("telephone", phoneNum.getText().toString());
 ClientKey.put("apprealname", realName.getText().toString());
 ClientKey.put("email", emailNum.getText().toString());
 ClientKey.put("sex", sex);

 /*封装Person数组*/
 JSONObject params = new JSONObject();
 params.put("Person", ClientKey);
 /*把JSON数据转换成String类型使用输出流向服务器写*/
 String content = String.valueOf(params);

 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 conn.setConnectTimeout(5000);
 conn.setDoOutput(true);//设置允许输出
 conn.setRequestMethod("POST");
 conn.setRequestProperty("User-Agent", "Fiddler");
 conn.setRequestProperty("Content-Type", "application/json");
 conn.setRequestProperty("Charset", encoding); 
 OutputStream os = conn.getOutputStream();
 os.write(content.getBytes());
 os.close();
 /*服务器返回的响应码*/
 int code = conn.getResponseCode();
 if(code == 200)
 {
 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
 String retData = null;
 String responseData = "";
 while((retData = in.readLine()) != null)
 {
 responseData += retData;
 }
 JSONObject jsonObject = new JSONObject(responseData);
 JSONObject succObject = jsonObject.getJSONObject("regsucc");
 //System.out.println(result);
 String success = succObject.getString("id");

 in.close();
 //System.out.println(success);
 Toast.makeText(Register.this, success, Toast.LENGTH_SHORT).show();
 Intent intentToLogin=new Intent();
 intentToLogin.setClass(Register.this,Login.class);
 startActivity(intentToLogin);
 finish();
 }
 else 
 {
 Toast.makeText(getApplicationContext(), "数据提交失败", Toast.LENGTH_SHORT).show();
 }
 } 
 catch (Exception e) 
 {
 // TODO: handle exception
 throw new RuntimeException(e);
 }
 Looper.loop(); 
 }

 }.start();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值