androidhttp请求实现session传递与传递参数
在最近写的⼀个Android中需要请求web服务器中的数据,有⼀个登录Activity,登录后会到MainActivity,这中间登录和MainActivity都需要请求php的jsonapi,所以要在⽹络请求中保持session的,研究了好半天才搞定。其实sesion在浏览器和web服务器直接是通过⼀个叫做name 为sessionid的cookie来传递的,所以只要在每次数据请求时保持sessionid是同⼀个不变就可以⽤到web的session了,做法是第⼀次数据请求时就获取sessionid的值并保存在⼀个静态变量中,然后在第⼆次请求数据的时候要将这个sessionid⼀并放在Cookie中发给服务器,服务器则是通过这个sessionid来识别究竟是那个客户端在请求数据的,在php中这个sessionid的名字叫做PHPSESSID。下⾯贴下代码
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.ity.UrlEncodedFormEntity;
import org.apache.hods.HttpPost;
import org.kie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class MyHttpClient implements InetConfig {
private DefaultHttpClient httpClient;
private HttpPost httpPost;
private HttpEntity httpEntity;
private HttpResponse httpResponse;
public static String PHPSESSID = null;
public LVHttpClient() {
}
public String executeRequest(String path, List<NameValuePair> params) {
String ret = "none";
try {
this.httpPost = new HttpPost(BASEPATH + path);
httpEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
httpPost.setEntity(httpEntity);
//第⼀次⼀般是还未被赋值,若有值则将SessionId发给服务器
if(null != PHPSESSID){
httpPost.setHeader("Cookie", "PHPSESSID=" + PHPSESSID);
}
httpClient = new DefaultHttpClient();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
httpResponse = ute(httpPost);
if (StatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = Entity();
ret = String(entity);
CookieStore mCookieStore = CookieStore();
List<Cookie> cookies = Cookies();
for (int i = 0; i < cookies.size(); i++) {
//这⾥是读取Cookie['PHPSESSID']的值存在静态变量中,保证每次都是同⼀个值
if ("PHPSESSID".(i).getName())) {
PHPSESSID = (i).getValue();
break;
}
}
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
}
其实web的原理都是⼀样的,基于http协议的,那么如果⽹站不是php做的话,那个叫做Sessionid的Cookie可能叫做别的了,就不是PHPSESSID了,⽽是叫做别的名字了,这个可能要具体情况去查了。
其实不只是Android程序,其他任何程序需要这么⽤的时候只需要在http协议请求header⾥头加上发送相应的SessionId就可以了。刚刚这种⽅法是可以帮助理解sessionid的,其实还有⼀种⽅法如果更通⽤的话,就可以将刚刚所有的Cookie每次都发回到服务器端,也就可以解决session保持的问题了,只是这样可能会稍微⼤些⽹络流量开销⽽已。
这⾥看到⼀个,顺便mark⼀下。
ps:不知道sessionid的名称可以把全部打出看
List<Cookie> cookies = d.getCookieStore().getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.(i).getName()+":"+(i).getValue());
}
post请求
⼆:传递参数
public void update(final String _sessionid,final String id)
{
new Thread(new Runnable(){
public void run() {
String serverURL = "youurl";
HttpPost httpRequest = new HttpPost(serverURL);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
try {
nameValuePair.add(new BasicNameValuePair("id",id));
nameValuePair.add(new BasicNameValuePair("name","hello"));
nameValuePair.add(new BasicNameValuePair("type","world"));
nameValuePair.add(new BasicNameValuePair("load_time","2014-11-15 10:10:00"));
nameValuePair.add(new BasicNameValuePair("expiration_time","2014-11-15 03:00:00")); httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (Exception e1) {
}
HttpResponse httpResponse2;
try
{
httpRequest.setHeader("Cookie", "laravel_session=" + new Tools().getSession());
httpResponse2 = new DefaultHttpClient().execute(httpRequest);
int ssconde = StatusLine().getStatusCode();
if (ssconde == 200)
{
String resu = Entity());// 获取返回的相应的字符串 System.out.println(resu);
}
}
catch (Exception e){
System.out.println("更新报错:"+e);
}
}}).start();
}
传参数设置编码:
httpRequest.setEntity(new UrlEncodedFormEntity(_nameValuePair,"utf-8"));
01. /*必需引⽤apache.http相关类别来建⽴HTTP联机*/
02. import org.apache.http.HttpResponse;
03. import org.apache.http.NameValuePair;
04. import org.apache.http.client.ClientProtocolException;el表达式获取session中的值
05. import org.apache.ity.UrlEncodedFormEntity;
06. import org.apache.hods.HttpGet;
07. import org.apache.hods.HttpPost;
08. import org.apache.http.impl.client.DefaultHttpClient;
09. import org.ssage.BasicNameValuePair;
10. import org.apache.http.protocol.HTTP;
11. import org.apache.http.util.EntityUtils;
12. /*必需引⽤java.io 与java.util相关类来读写⽂件*/
13. import java.io.IOException;
14. import java.util.ArrayList;
15. import java.util.List;
16. import Matcher;
17. import Pattern;
18.
19. import android.app.Activity;
20. import android.os.Bundle;
21. import android.view.View;
22. import android.widget.Button;
23. import android.widget.TextView;
24.
25. public class EX08_01 extends Activity
26. {
27. /*声明两个Button对象,与⼀个TextView对象*/
28. private Button mButton1,mButton2;
29. private TextView mTextView1;
30.
31. /** Called when the activity is first created. */
32. @Override
33. public void onCreate(Bundle savedInstanceState)
34. {
35. Create(savedInstanceState);
36. setContentView(R.layout.main);
37.
38. /*透过findViewById建构⼦建⽴TextView与Button对象*/
39. mButton1 =(Button) findViewById(Button1);
40. mButton2 =(Button) findViewById(Button2);
41. mTextView1 = (TextView) findViewById(TextView1);
42.
43. /*设定OnClickListener来聆听OnClick事件*/
44. mButton1.setOnClickListener(new Button.OnClickListener()
45. {
46. /*重写onClick事件*/
47. @Override
48. public void onClick(View v)
49. {
50. /*声明⽹址字符串*/
51. String uriAPI = ":8751/Android/Test/API/Post/index.php";
52. /*建⽴HTTP Post联机*/
53. HttpPost httpRequest = new HttpPost(uriAPI);
54. /*
55. * Post运作传送变量必须⽤NameValuePair[]数组储存
56. */
57. List <NameValuePair> params = new ArrayList <NameValuePair>();
58. params.add(new BasicNameValuePair("str", "I am Post String"));
59. try
60. {
61. /*发出HTTP request*/
62. httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
63. /*取得HTTP response*/
64. HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
65. /*若状态码为200 ok*/
66. StatusLine().getStatusCode() == 200)
67. {
68. /*取出响应字符串*/
69. String strResult = Entity());
70. mTextView1.setText(strResult);
71. }
72. else
73. {
74. mTextView1.setText("Error Response: "+StatusLine().toString());
75. }
76. }
77. catch (ClientProtocolException e)
78. {
79. mTextView1.Message().toString());
80. e.printStackTrace();
81. }
82. catch (IOException e)
83. {
84. mTextView1.Message().toString());
85. e.printStackTrace();
86. }
87. catch (Exception e)
88. {
89. mTextView1.Message().toString());
90. e.printStackTrace();
91. }
92.
93. }
94. });
95. mButton2.setOnClickListener(new Button.OnClickListener()
96. {
97. @Override
98. public void onClick(View v)
99. {
100. // TODO Auto-generated method stub
101. /*声明⽹址字符串*/
102. String uriAPI = ":8751/Android/Test/API/Get/index.php?str=I+am+Get+String"; 103. /*建⽴HTTP Get联机*/
104. HttpGet httpRequest = new HttpGet(uriAPI);
105. try
106. {
107. /*发出HTTP request*/
108. HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
109. /*若状态码为200 ok*/
110. StatusLine().getStatusCode() == 200)
111. {
112. /*取出响应字符串*/
113. String strResult = Entity());
114. /*删除多余字符*/
115. strResult = eregi_replace("(/r/n|/r|/n|/n/r)","",strResult);
116. mTextView1.setText(strResult);
117. }
118. else
119. {
120. mTextView1.setText("Error Response: "+StatusLine().toString());
121. }
122. }
123. catch (ClientProtocolException e)
124. {
125. mTextView1.Message().toString());
126. e.printStackTrace();
127. }
128. catch (IOException e)
129. {
130. mTextView1.Message().toString());
131. e.printStackTrace();
132. }
133. catch (Exception e)
134. {
135. mTextView1.Message().toString());
136. e.printStackTrace();
137. }
138. }
139. });
140. }
141. /* ⾃定义字符串取代函数 */
142. public String eregi_replace(String strFrom, String strTo, String strTarget)
143. {
144. String strPattern = "(?i)"+strFrom;
145. Pattern p = Patternpile(strPattern);
146. Matcher m = p.matcher(strTarget);
147. if(m.find())
148. {
149. placeAll(strFrom, strTo);
150. }
151. else
152. {
153. return strTarget;
154. }
155. }
156. }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论