HttpClient tool class in HttpPost.setHeader("Cookie", "PHPSESSID=" + PHPSESSID) method

Abstract: The  session is directly passed between the browser and the web server through a cookie named sessionid, so as long as the sessionid is kept the same for each data request, the web session can be used. The method is the first When a data request is made, the value of the sessionid is obtained and stored in a static variable, and then when the data is requested for the second time, the sessionid should be placed in a cookie and sent to the server. The server uses this sessionid to identify it.

The session is directly passed between the browser and the web server through a cookie named sessionid, so as long as the sessionid is kept the same for each data request, the web session can be used. This is the first time. When the data is requested, the value of the sessionid is obtained and stored in a static variable. Then, when the data is requested for the second time, the sessionid should be placed in a cookie and sent to the server. The server uses this sessionid to identify which one is. When the client is requesting data, the name of the sessionid in php is called PHPSESSID. The name of sessionid under java is called JSESSIONID  

package com.rainet.tiis.network;  
  
import java.util.Iterator;  
import java.util.List;  
import java.util.Map;  
  
import org.apache.http.HttpResponse;  
import org.apache.http.NameValuePair;  
import org.apache.http.client.CookieStore;  
import org.apache.http.client.HttpClient;  
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.client.params.HttpClientParams;  
import org.apache.http.cookie.Cookie;  
import org.apache.http.impl.client.DefaultHttpClient;  
import org.apache.http.params.BasicHttpParams;  
import org.apache.http.params.HttpConnectionParams;  
import org.apache.http.params.HttpParams;  
import org.apache.http.params.HttpProtocolParams;  
import org.apache.http.protocol.HTTP;  
import org.apache.http.util.EntityUtils;  
  
import android.util.Log;  
  
/**
 * @project: TIIS  
 * @Title:                      SimpleClient.java        
 * @Package                     com.rainet.tiis.network      
 * @Description: HTTP request factory
 * @author Yang Guisong    
 * @date 2014-3-18 12:39:23 PM  
 * @version                     V1.0
 */  
public class SimpleClient {  
    private static HttpParams httpParams;  
    private static DefaultHttpClient httpClient;  
    private static String JSESSIONID; //Define a static field to save sessionID  
  
    /**
     * @Title:              getHttpClient  
     * @author Yang Guisong
     * @date 2014-3-18 1:11:18 PM
     * @Description: Get HttpClient
     * @return
     * @throws Exception  
     * HttpClient returns
     */  
    public static HttpClient getHttpClient() throws Exception {  
        // Create HttpParams for setting HTTP parameters (this part is not required)  
        httpParams = new BasicHttpParams();  
        // Set connection timeout and socket timeout, and socket cache size  
        HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);  
        HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);  
        HttpConnectionParams.setSocketBufferSize(httpParams, 8192);  
        // set redirection, default is true  
        HttpClientParams.setRedirecting (httpParams, true);  
        // set user agent  
        String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";  
        HttpProtocolParams.setUserAgent(httpParams, userAgent);  
        // Create an instance of HttpClient  
        // 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient  
        // usage, in Android 1.5 we need to use Apache's default implementation DefaultHttpClient  
        httpClient = new DefaultHttpClient(httpParams);  
        return httpClient;  
    }  
  
    /**
     * @Title:              doGet  
     * @author Yang Guisong
     * @date 2014-3-18 12:39:58 PM
     * @Description: doGet request
     * @param url
     * @param params
     * @return
     * @throws Exception  
     * String return
     */  
    @SuppressWarnings("rawtypes")  
    public static String doGet(String url, Map params) throws Exception {  
        /* Create HTTPGet object */  
        String paramStr = "";  
        if (params != null) {  
            Iterator iter = params.entrySet().iterator();  
            while (iter.hasNext()) {  
                Map.Entry entry = (Map.Entry) iter.next();  
                Object key = entry.getKey();  
                Object val = entry.getValue();  
                paramStr += paramStr = "&" + key + "=" + val;  
            }  
        }  
        if (!paramStr.equals("")) {  
            paramStr = paramStr.replaceFirst("&", "?");  
            url += paramStr;  
        }  
        HttpGet httpRequest = new HttpGet(url);  
        String strResult = "doGetError";  
        /* send request and wait for response */  
        HttpResponse httpResponse = httpClient.execute(httpRequest);  
        /* If the status code is 200 ok */  
        if (httpResponse.getStatusLine().getStatusCode() == 200) {  
            /* read return data */  
            strResult = EntityUtils.toString(httpResponse.getEntity());  
        } else {  
            strResult = "Error Response: " + httpResponse.getStatusLine().toString();  
        }  
        Log.v("strResult", strResult);  
        return strResult;  
    }  
  
    /**
     * @Title:              doPost  
     * @author Yang Guisong
     * @date 2014-3-18 12:39:38 PM
     * @Description: doPost request
     * @param url
     * @param params
     * @return
     * @throws Exception  
     * String return
     */  
    public static String doPost(String url, List<NameValuePair> params) throws Exception {  
        /* Create HTTPPost object */  
        HttpPost httpRequest = new HttpPost(url);  
        String strResult = "doPostError";  
        /* Add request parameters to the request object */  
        if (params != null && params.size() > 0) {  
            httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
        }  
        if(null != JSESSIONID){  
            httpRequest.setHeader("Cookie", "JSESSIONID="+JSESSIONID);  
        }  
        /* send request and wait for response */  
        HttpResponse httpResponse = httpClient.execute(httpRequest);  
        /* If the status code is 200 ok */  
        if (httpResponse.getStatusLine().getStatusCode() == 200) {  
            /* read return data */  
            strResult = EntityUtils.toString(httpResponse.getEntity());  
            /* Get cookieStore */  
            CookieStore cookieStore = httpClient.getCookieStore();  
            List<Cookie> cookies = cookieStore.getCookies();  
            for(int i=0;i<cookies.size();i++){  
 //Here is to read the value of Cookie['JSSESSID'] and store it in a static variable to ensure that it is the same value every time
                if("JSESSIONID".equals(cookies.get(i).getName())){  
                    JSESSIONID = cookies.get(i).getValue();  
                    break;  
                }  
            }  
        }  
        Log.v("strResult", strResult);  
        return strResult;  
    }  
  
}  
(4.1.28.2) HttpClient tool class in HttpPost.setHeader("Cookie", "PHPSESSID=" + PHPSESSID) method

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325551425&siteId=291194637