在最近写的一个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.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.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 = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = httpResponse.getEntity(); ret = EntityUtils.toString(entity); CookieStore mCookieStore = httpClient.getCookieStore(); List<Cookie> cookies = mCookieStore.getCookies(); for (int i = 0; i < cookies.size(); i++) { //这里是读取Cookie['PHPSESSID']的值存在静态变量中,保证每次都是同一个值 if ("PHPSESSID".equals(cookies.get(i).getName())) { PHPSESSID = cookies.get(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保持的问题了,只是这样可能会稍微大些网络流量开销而已。
这里看到一个SessionId的本质,顺便mark一下。
ps:不知道sessionid的名称可以把全部打出看
List<Cookie> cookies = d.getCookieStore().getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.println(cookies.get(i).getName()+":"+cookies.get(i).getValue());
}
post请求
http://blog.csdn.net/tianyitianyi1/article/details/8302014
二:传递参数
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 = httpResponse2.getStatusLine().getStatusCode();
if (ssconde == 200)
{
String resu = EntityUtils.toString(httpResponse2.getEntity());// 获取返回的相应的字符串
System.out.println(resu);
}
}
catch (Exception e){
System.out.println("更新报错:"+e);
}
}}).start();
}
传参数设置编码:
httpRequest.setEntity(new UrlEncodedFormEntity(_nameValuePair,"utf-8"));
- /*必需引用apache.http相关类别来建立HTTP联机*/
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- /*必需引用java.io 与java.util相关类来读写文件*/
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- public class EX08_01 extends Activity
- {
- /*声明两个Button对象,与一个TextView对象*/
- private Button mButton1,mButton2;
- private TextView mTextView1;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- /*透过findViewById建构子建立TextView与Button对象*/
- mButton1 =(Button) findViewById(R.id.myButton1);
- mButton2 =(Button) findViewById(R.id.myButton2);
- mTextView1 = (TextView) findViewById(R.id.myTextView1);
- /*设定OnClickListener来聆听OnClick事件*/
- mButton1.setOnClickListener(new Button.OnClickListener()
- {
- /*重写onClick事件*/
- @Override
- public void onClick(View v)
- {
- /*声明网址字符串*/
- String uriAPI = "http://www.dubblogs.cc:8751/Android/Test/API/Post/index.php";
- /*建立HTTP Post联机*/
- HttpPost httpRequest = new HttpPost(uriAPI);
- /*
- * Post运作传送变量必须用NameValuePair[]数组储存
- */
- List <NameValuePair> params = new ArrayList <NameValuePair>();
- params.add(new BasicNameValuePair("str", "I am Post String"));
- try
- {
- /*发出HTTP request*/
- httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
- /*取得HTTP response*/
- HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
- /*若状态码为200 ok*/
- if(httpResponse.getStatusLine().getStatusCode() == 200)
- {
- /*取出响应字符串*/
- String strResult = EntityUtils.toString(httpResponse.getEntity());
- mTextView1.setText(strResult);
- }
- else
- {
- mTextView1.setText("Error Response: "+httpResponse.getStatusLine().toString());
- }
- }
- catch (ClientProtocolException e)
- {
- mTextView1.setText(e.getMessage().toString());
- e.printStackTrace();
- }
- catch (IOException e)
- {
- mTextView1.setText(e.getMessage().toString());
- e.printStackTrace();
- }
- catch (Exception e)
- {
- mTextView1.setText(e.getMessage().toString());
- e.printStackTrace();
- }
- }
- });
- mButton2.setOnClickListener(new Button.OnClickListener()
- {
- @Override
- public void onClick(View v)
- {
- // TODO Auto-generated method stub
- /*声明网址字符串*/
- String uriAPI = "http://www.dubblogs.cc:8751/Android/Test/API/Get/index.php?str=I+am+Get+String";
- /*建立HTTP Get联机*/
- HttpGet httpRequest = new HttpGet(uriAPI);
- try
- {
- /*发出HTTP request*/
- HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
- /*若状态码为200 ok*/
- if(httpResponse.getStatusLine().getStatusCode() == 200)
- {
- /*取出响应字符串*/
- String strResult = EntityUtils.toString(httpResponse.getEntity());
- /*删除多余字符*/
- strResult = eregi_replace("(/r/n|/r|/n|/n/r)","",strResult);
- mTextView1.setText(strResult);
- }
- else
- {
- mTextView1.setText("Error Response: "+httpResponse.getStatusLine().toString());
- }
- }
- catch (ClientProtocolException e)
- {
- mTextView1.setText(e.getMessage().toString());
- e.printStackTrace();
- }
- catch (IOException e)
- {
- mTextView1.setText(e.getMessage().toString());
- e.printStackTrace();
- }
- catch (Exception e)
- {
- mTextView1.setText(e.getMessage().toString());
- e.printStackTrace();
- }
- }
- });
- }
- /* 自定义字符串取代函数 */
- public String eregi_replace(String strFrom, String strTo, String strTarget)
- {
- String strPattern = "(?i)"+strFrom;
- Pattern p = Pattern.compile(strPattern);
- Matcher m = p.matcher(strTarget);
- if(m.find())
- {
- return strTarget.replaceAll(strFrom, strTo);
- }
- else
- {
- return strTarget;
- }
- }
- }
http://blog.csdn.net/flying_tao/article/details/6553601
http://www.kwstu.com/ArticleView/kwstu_201332284332504