Android给服务器发送json数据初体验
2015-11-30 10:36
579 查看
new Thread() { @Override public void run() { // TODO Auto-generated method stub Looper.prepare(); final String urlPath="http://rc-ws.mymhotel.com/hotelservice/checkin/service/add_task.do"; URL url; try { url = new URL(urlPath); /*下面是发送给服务器的json文本*/ JSONObject jsonObj = new JSONObject(); jsonObj.put("diviceId", "CDSY00051") .put("location", "速八酒店") .put("locationArea", "铜锣湾红星社团") .put("timeLimit", "2015-11-30 10:11:29") .put("priority", 0) .put("patternInfo", 1) .put("category", "0") .put("messageInfo", "三斤牛肉") .put("locationDesc", "商务中心301"); /*把JSON数据转换成String类型使用输出流向服务器写*/ /*格式为:sendcontent={"diviceId":"CDSY00051","location":"速八酒店","locationArea":"铜锣湾红星社团", "timeLimit":"2015-11-30 16:58:29","priority":0,"patternInfo":1,"category":"0","messageInfo":"三斤牛肉", "locationDesc":"商务中心301"} */ // String sendcontent = String.valueOf(jsonObj); String sendcontent = jsonObj.toString(); Log.d("CallServiceActivity", "sendcontent=" + sendcontent); 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", "utf-8"); OutputStream os = conn.getOutputStream(); os.write(sendcontent.getBytes()); os.close(); /*服务器返回的响应码*/ int code = conn.getResponseCode(); if(code == 200) { //这里接收服务器返回的数据(如:responseData={"taskCode":"s2015113010041049003"}) BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String retData = null; String responseData = ""; while((retData = in.readLine()) != null) { responseData += retData; } JSONObject jsonObject = new JSONObject(responseData); String success = "发送成功啦"; //打印输出服务器返回的数据 Log.d("CallServiceActivity","成功啦responseData="+responseData); in.close(); //System.out.println(success); Toast.makeText(CallServiceActivity.this, success, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "数据提交失败", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { // TODO: handle exception throw new RuntimeException(e); } Looper.loop(); } }.start();
相关文章推荐
- android解析服务器传来的xml文件和json文件(一)
- Android ReceiverCallNotAllowedException: BroadcastReceiver components are not allowed to register to receive intents
- Android 内存优化
- android.view.view
- android 百度地图开发
- android将Bitmap转换成文件
- Android 中使用的设计模式
- 开源photoview
- Android 颜色值透明度效果设置
- android touch事件分发、拦截和响应分析
- android ContentObserver和DatasetObserver的区别
- android 开机默认语言等其它默认配置项的配置
- Android USB Host的使用详解
- android gradle配置
- android ScrollView滚动距离和判断滚动停止状态
- android:windowSoftInputMode属性详解
- android gridview 属性集合
- android studio 使用retrolambda库 让代码支持lambda 表达式
- android属性动画
- android使用上下文context浅说