更新时间:2023-11-27 23:18:28
在大量的研究和许多例子后,我终于成功地登录到该网站,我试图。显然,这是一个问题,我没有从响应消费实体,即饼干。我创建了一个简单的活动谁的主要目的是GET和POST到网站,然后吐了出来,结果到LogCat中。或许,这可以帮助别人。
After much research and many examples later I have finally managed to login to the site I was attempting. Apparently It was an issue with me not consuming the entity from the response, ie the cookies. I created a simple activity who's main purpose is to GET and POST to the site then spit out the result into LogCat. Perhaps this may help others.
public class HttpClientTest extends Activity{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request;
HttpEntity entity;
List<Cookie> cookies;
HttpResponse response;
HttpPost post;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
getRequest();
} catch (Exception e) {
Log.d("My Activity", "Failed");
e.printStackTrace();
}
}
public void getRequest() throws Exception
{
final String TAG = "MyActivity";
request = new HttpGet("http://some.site.com/");
response = client.execute(request);
entity = response.getEntity();
Log.d(TAG, "Login form get: " + response.getStatusLine());
if(entity != null)
{
entity.consumeContent();
}
Log.d(TAG, "Initial set of cookies:");
cookies = client.getCookieStore().getCookies();
if (cookies.isEmpty())
{
Log.d(TAG, "None");
}
else
{
for(int i = 0; i<cookies.size(); i++)
{
Log.d(TAG, "- " + cookies.get(i));
}
}
String action = "i.cfm?&1028&p=login&se=4";
String yourServer = "http://some.site.com/";
post = new HttpPost(yourServer + action);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("nic", "username"));
params.add(new BasicNameValuePair("password", "password"));
params.add(new BasicNameValuePair("server", "4"));
post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
response = client.execute(post);
entity = response.getEntity();
Log.d(TAG, "Login form get: " + response.getStatusLine());
if(entity != null){
entity.consumeContent();
}
Log.d(TAG, "Post logon cookies:");
cookies = client.getCookieStore().getCookies();
if (cookies.isEmpty())
{
Log.d(TAG, "None");
}
else
{
for (int i = 0; i < cookies.size(); i++)
{
Log.d(TAG, "- " + cookies.get(i));
}
}
request = new HttpGet("http://some.site.com/i.cfm?f=com_empire&cm=3");
response = client.execute(request);
Log.d(TAG, "Check for login: " + Parser.request(response));
if(entity != null)
{
entity.consumeContent();
}
}
}
最后一个日志,Log.d(TAG,检查登入:+ Parser.request(响应));打印出网站的HTML所经历一个解析类,这是我用来验证,这是逸岸一个页面,需要登录成功
the last log, Log.d(TAG, "Check for login: " + Parser.request(response)); prints out the html of the site by going through a parser class, which I used to verify that it was infact a page that required successful login