标签:android style blog http java color
在连接服务器数据库时需要使用以上包中的类,使用json格式传送
1 public static String Register(String username,String password,int operator) throws Exception 2 { 3 String returnString = "Failed"; 4 String []urlString = {"http://test.inscut.com/android/register.php","http://test.inscut.com/android/login.php"}; 5 HttpPost httpPost = new HttpPost(urlString[operator]); 6 //params:send to server 7 ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); 8 params.add(new BasicNameValuePair("username", username)); 9 params.add(new BasicNameValuePair("password", password)); 10 try { 11 httpPost.setEntity(new UrlEncodedFormEntity(params,"utf8")); 12 } catch (UnsupportedEncodingException e) { 13 // TODO Auto-generated catch block 14 e.printStackTrace(); 15 } 16 //send post return HttpResponse object 17 HttpResponse response = null; 18 try { 19 response = new DefaultHttpClient().execute(httpPost); 20 } catch (ClientProtocolException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } catch (IOException e) { 24 // TODO Auto-generated catch block 25 e.printStackTrace(); 26 } 27 if(response!=null) 28 { 29 int res = response.getStatusLine().getStatusCode(); 30 if(res==200) 31 { 32 HttpEntity entity = response.getEntity(); 33 if(entity!=null) 34 { 35 String info=null; 36 try 37 { 38 info = EntityUtils.toString(entity); 39 } catch (ParseException e) 40 { 41 e.printStackTrace(); 42 } catch (IOException e) 43 { 44 e.printStackTrace(); 45 } 46 if(info!=null) 47 { 48 JSONObject jsonObject = new JSONObject(info); 49 if(jsonObject.getString("flag").equals("success")) 50 { 51 returnString = "Success"; 52 if(operator==1) 53 returnString = jsonObject.getString("session_id"); 54 } 55 56 } 57 } 58 } 59 } 60 return returnString; 61 }
简单介绍下java同步数据库的流程:
1.使用java http类库向服务器发送http请求,
HttpPost httpPost = new HttpPost(urlString[operator]);
//params 是请求附带参数
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
//给http请求设置实体部分,既将参数添加到http报文中
httpPost.setEntity(new UrlEncodedFormEntity(params,"utf8"));
//通过一个httpclient发送post请求
response = new DefaultHttpClient().execute(httpPost);
2.服务器返回处理结果,本例中使返回一个session_id值
int res = response.getStatusLine().getStatusCode();//返回信息的状态码,200表示正常(状态码是为了便于区分本次请求的结果如何,像常见的404,意味着你请求的网页找不到)
HttpEntity entity = response.getEntity();//获得返回http的实体部分,返回数据存在于http的实体部分
info = EntityUtils.toString(entity);
其实只看代码是有点难理解的,建议看完《HTTP权威指南》前四章,就能更加清楚的理解http
标签:android style blog http java color
原文地址:http://www.cnblogs.com/lethe-xt/p/3826947.html