安卓访问网络后台通用算法json请求方式

安卓访问网络后台通用算法
 HttpPost request = new HttpPost(SERVER_URL); // 这里的SERVER_URL是一个url加上对应网页中的方法名
//例如 http://123.234.8.219:81/epos-wuji.asmx/CreateOrder01

request.addHeader("Content-Type", "application/json; charset=utf-8");
// 必须要添加该Http头才能调用WebMethod时返回JSON数据

JSONObject jsonParams = new JSONObject();      

try {
                                                          //根据后台要求填写JSONbject 类的实例对象,用put(,)方法填写
//这里需要用try{}catch(...){}来捕获异常 
jsonParams.put("uid", m_uid);
jsonParams.put("amt", m_amt);
jsonParams.put("pid", m_pid);
jsonParams.put("note", m_note);
jsonParams.put("type", 0);
jsonParams.put("type0", 0);

} catch (JSONException e1) {
//System.out.println("JSON插入错误");
e1.printStackTrace();
}

HttpEntity bodyEntity = null;       //声明一个HttpEntity 的对象        
try {
bodyEntity = new StringEntity(jsonParams.toString(), "utf8");
} catch (UnsupportedEncodingException e2) {
//System.out.println("SoapFault1```响应错误···" + e2.toString());
e2.printStackTrace();
}
// 参数必须也得是JSON数据格式的字符串才能传递到服务器端,否则会出现"{'Message':'strUserName是无效的JSON基元'}"的错误

request.setEntity(bodyEntity);

HttpResponse httpResponse = null;
try {
httpResponse = new DefaultHttpClient().execute(request);
} catch (ClientProtocolException e2) {
System.out.println("SoapFault2```响应错误···" + e2.toString());
e2.printStackTrace();
} catch (IOException e2) {
System.out.println("SoapFault3```响应错误···" + e2.toString());
e2.printStackTrace();
} // 发送请求并获取反馈

if (httpResponse.getStatusLine().getStatusCode() == 200) {

System.out.println("连接成功");
}

if (httpResponse.getStatusLine().getStatusCode() != 404)
// StatusCode为200表示与服务端连接成功,404为连接不成功

{
// x
System.out.println("连接返回码!=404");

String result = null;
try {
result = EntityUtils.toString(httpResponse.getEntity());
} catch (ParseException e1) {
System.out.println("SoapFault4```响应错误···" + e1.toString());
e1.printStackTrace();
} catch (IOException e1) {
System.out.println("SoapFault4```响应错误···" + e1.toString());
e1.printStackTrace();
}

JSONObject resultJSON = null;
try {
resultJSON = new JSONObject(result);

} catch (JSONException e) {
System.out.println("解析错误*****" + e.toString());
e.printStackTrace();
}
try {
String orderNumber = resultJSON.get("d").toString();

Message mes = handler.obtainMessage(); // 登录成功
mes.what = 0;
mes.obj = orderNumber;
handler.sendMessage(mes);

System.out.println("提前检查" + resultJSON.get("d").toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("整体效果" + resultJSON);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郑剑1996

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值