Android客户端与服务器HTTP交互,数据以json格式传输
jopen
10年前
/** * HTTP请求服务器 * @author lz */ public class HttpRequestServer{ private String serverCategoryStr = "http://192.168.1.2:8080/ChatXXX/";// 服务器地址 private String url = "http://192.168.1.4:8080/ChatXXX/login"; private static final int REQUEST_TIMEOUT = 1 * 1000;// 设置请求超时10秒钟 private static final int SO_TIMEOUT = 5 * 1000; // 设置等待数据超时时间10秒钟 private static final int type=-1;//请求Type public HttpRequestServer() { } /** * 用户登录 * @param name * @param pwd * @return * @throws ClientProtocolException * @throws JSONException * @throws IOException */ public JSONObject login(String name, String pwd) throws ClientProtocolException, JSONException, IOException { url = serverCategoryStr + Constants.URL_LOGIN; JSONObject param = new JSONObject(); param.put(Constants.TYPE, Constants.LOGIN); param.put(Constants.USER_NAME, name); param.put(Constants.USER_PASSWORD, pwd); return requestServer(Constants.LOGIN, param); } /** * 通用请求服务器函数 * @param userId * @param name * @param pwd * @param requestType * @param status * @return * @throws JSONException * @throws ClientProtocolException * @throws IOException */ private JSONObject requestServer(String requestType,JSONObject param) throws JSONException, ClientProtocolException, IOException { // 不加这一段则会报错,错误信息为android.os.networkonmainthreadexception // 在Android2.2以后必须添加以下代码 // 本应用采用的Android4.0 // 设置线程的策略 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .permitAll() // 此处为允许磁盘读写和网络访问 .penaltyLog() // 打印logcat,当然也可以定位到dropbox,通过文件保存相应的log .build()); HttpPost request = new HttpPost(url); // 绑定到请求 Entry StringEntity se = new StringEntity(param.toString(),"utf-8"); request.setEntity(se); // 发送请求 HttpClient httpclient = getHttpClient(); HttpResponse httpResponse = httpclient.execute(request); JSONObject result = null; int code=httpResponse.getStatusLine().getStatusCode(); if (code == 200) { // 得到应答的字符串,这也是一个 JSON 格式保存的数据 String retSrc = null; retSrc = EntityUtils.toString(httpResponse.getEntity(),"utf-8"); JSONObject jtmpJsonObject = new JSONObject(retSrc); String str = jtmpJsonObject.getString("dataMap");// 此处"dataMap"与服务器关联 result = new JSONObject(str); } return result; } private HttpClient getHttpClient() { BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT); HttpClient httpclient = new DefaultHttpClient(httpParams); return httpclient; }