您的位置:首页 > 移动开发 > Android开发

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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: