安卓访问网络后台通用算法
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);
}