android http请求实现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.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"));


  1. /*必需引用apache.http相关类别来建立HTTP联机*/  
  2. import org.apache.http.HttpResponse;   
  3. import org.apache.http.NameValuePair;   
  4. import org.apache.http.client.ClientProtocolException;   
  5. import org.apache.http.client.entity.UrlEncodedFormEntity;   
  6. import org.apache.http.client.methods.HttpGet;  
  7. import org.apache.http.client.methods.HttpPost;   
  8. import org.apache.http.impl.client.DefaultHttpClient;   
  9. import org.apache.http.message.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 java.util.regex.Matcher;  
  17. import java.util.regex.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.     super.onCreate(savedInstanceState);   
  36.     setContentView(R.layout.main);   
  37.        
  38.     /*透过findViewById建构子建立TextView与Button对象*/   
  39.     mButton1 =(Button) findViewById(R.id.myButton1);   
  40.     mButton2 =(Button) findViewById(R.id.myButton2);  
  41.     mTextView1 = (TextView) findViewById(R.id.myTextView1);   
  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 = "http://www.dubblogs.cc: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.           if(httpResponse.getStatusLine().getStatusCode() == 200)    
  67.           {   
  68.             /*取出响应字符串*/  
  69.             String strResult = EntityUtils.toString(httpResponse.getEntity());   
  70.             mTextView1.setText(strResult);   
  71.           }   
  72.           else   
  73.           {   
  74.             mTextView1.setText("Error Response: "+httpResponse.getStatusLine().toString());   
  75.           }   
  76.         }   
  77.         catch (ClientProtocolException e)   
  78.         {    
  79.           mTextView1.setText(e.getMessage().toString());   
  80.           e.printStackTrace();   
  81.         }   
  82.         catch (IOException e)   
  83.         {    
  84.           mTextView1.setText(e.getMessage().toString());   
  85.           e.printStackTrace();   
  86.         }   
  87.         catch (Exception e)   
  88.         {    
  89.           mTextView1.setText(e.getMessage().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 = "http://www.dubblogs.cc: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.           if(httpResponse.getStatusLine().getStatusCode() == 200)    
  111.           {   
  112.             /*取出响应字符串*/  
  113.             String strResult = EntityUtils.toString(httpResponse.getEntity());  
  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: "+httpResponse.getStatusLine().toString());   
  121.           }   
  122.         }   
  123.         catch (ClientProtocolException e)   
  124.         {    
  125.           mTextView1.setText(e.getMessage().toString());   
  126.           e.printStackTrace();   
  127.         }   
  128.         catch (IOException e)   
  129.         {    
  130.           mTextView1.setText(e.getMessage().toString());   
  131.           e.printStackTrace();   
  132.         }   
  133.         catch (Exception e)   
  134.         {    
  135.           mTextView1.setText(e.getMessage().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 = Pattern.compile(strPattern);  
  146.       Matcher m = p.matcher(strTarget);  
  147.       if(m.find())  
  148.       {  
  149.         return strTarget.replaceAll(strFrom, strTo);  
  150.       }  
  151.       else  
  152.       {  
  153.         return strTarget;  
  154.       }  
  155.     }  
  156. }   


http://blog.csdn.net/flying_tao/article/details/6553601

http://www.kwstu.com/ArticleView/kwstu_201332284332504




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值