【转载】Android基于HTTP header的用户Authentication

来源:互联网 发布:晋业进销存软件8.25 编辑:程序博客网 时间:2024/06/11 16:53

转自我的github博客,In Pursuit of Absolute Simplicity

博文地址,http://jesusjzp.github.io/blog/2013/08/12/Android-Develop-Record/


目前项目因为临时没有建立用户数据,所以选择使用http header加载用户信息,通常http头部信息如下:

2011-02-23 15:37:36: (request.c.304) fd: 8 request-len: 308POST /test.php HTTP/1.1Accept: application/jsonUser-Agent: Apache-HttpClient/4.1 (java 1.5)Host: myhost.comAuthorization: Basic YnxpcYRlc3RwMTulHGhlSGs=Content-Length: 21Content-Type: application/x-www-form-urlencoded; charset=UTF-8Content-Encoding: UTF-8Connection: Keep-AliveHTTP/1.1 200 OKContent-type: text/htmlTransfer-Encoding: chunked

Android代码如下:

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import org.apache.http.HttpResponse;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CookieStore;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.auth.BasicScheme;import org.apache.http.impl.client.AbstractHttpClient;import org.apache.http.impl.client.DefaultHttpClient;import android.util.Log;public class HttpGetMethod {public String getFoldersStats(String username, String password, String action) {String res = "";try {String url = URL ADDRESS+action;HttpGet httpReq = new HttpGet(url);// add header informationhttpReq.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(username, password),"UTF-8", false));DefaultHttpClient httpClient = new DefaultHttpClient();HttpResponse httpResponse = httpClient.execute(httpReq);// handler respondsStringBuilder builder = new StringBuilder();BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));for (String s = reader.readLine(); s != null; s = reader.readLine()) {builder.append(s);}res = builder.toString();// Save to cookieCookieStore cookieStore = ((AbstractHttpClient) httpClient).getCookieStore();} catch (Exception e) {Log.e("", e.toString());}return res;}}
原创粉丝点击