开发者社区> 问答> 正文

post请求 cookie不能同步的问题? 400 报错

post请求 cookie不能同步的问题? 400 报错 我先发次请求给学校的教务网,然后得到个cookie,将这个cookie加入到post请求的请求头中,再次发送给验证码页面,再次得到个cookie,但是。。。。问题来了:为什么这2次的cookie对象不一样了呢?如何才能使这2个对象一样了。。。

package com.example.mycookietest;

import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set;

import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.RedirectHandler; 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.ClientPNames; import org.apache.http.client.params.HttpClientParams; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.AbstractHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultRedirectHandler; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils;

import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.JsonReader; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{ HttpClient httpClient = new DefaultHttpClient(); //存放cookie的字符串
private static List<Cookie> cookieString; private static String cookies=""; private String string; private TextView textView; private Myhandler myhandler = new Myhandler(); private Bitmap bitmap; private ImageView imageView; private EditText name,psw,code; private Button send; private String res; private String viewstate; private boolean successed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textview1); imageView = (ImageView)findViewById(R.id.codeimg); name = (EditText)findViewById(R.id.name); psw=(EditText)findViewById(R.id.psw); code=(EditText)findViewById(R.id.code); send = (Button)findViewById(R.id.send); //绑定监听器 启动UI线 send.setOnClickListener(this); new UrlThread().start(); } private class GetCodeThread extends Thread{ @Override public void run() { try { getcode(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } super.run(); } } /** * UI线程 * @author Administrator * / private class UrlThread extends Thread { @Override public void run() { super.run(); try { httpget(); // getcode(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* * 获取保持回话的cookie对象 * @throws Exception */ public void httpget() throws Exception{ HttpPost httpPost = new HttpPost("http://jwxt.tit.edu.cn"); httpPost.setHeader("Connection","keep-alive"); HttpResponse httpResponse = httpClient.execute(httpPost); //System.out.println("这是页面的返回码------>"+httpResponse.getStatusLine().getStatusCode()); //获取网页的html字符串 // String htmlstr=EntityUtils.toString(httpResponse.getEntity()); // System.out.println("这是获取保持会话cookie返回的值------>"+htmlstr); // //分离字符串 // htmlstr = htmlstr.split(" name="__VIEWSTATE" value="")[1]; // //获取cookie对象 并且用分号隔开,第一部分里面存放的就是cookie的值 cookieString = ((AbstractHttpClient) httpClient).getCookieStore().getCookies(); String tag="text"; // for(Cookie c:cookieString){ // cookies+=c.toString()+";"; // } // System.out.println("这里是遍历后的cookie----->"+cookies); Log.i(tag, "这是获取到的Set-Cookie----->"+cookieString.get(0).getValue()); myhandler.sendEmptyMessage(0);

}
/**
 * 获取验证码
 * @throws Exception
 */
public void getcode() throws Exception{
	//验证码页面
	HttpPost httpPost = new HttpPost("http://jwxt.tit.edu.cn/sys/ValidateCode.aspx");

// httpPost.addHeader("Cookie","ASP.NET_SessionId="+cookieString); httpPost.setHeader("Cookie","ASP.NET_SessionId="+cookieString); httpPost.setHeader("Connection","keep-alive"); System.out.println("这是第一次请求的cookie----->"+cookieString.get(0).getValue()); httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false); HttpResponse httpResponse = httpClient.execute(httpPost); cookieString = ((AbstractHttpClient) httpClient).getCookieStore().getCookies(); System.out.println("这是第二次请求的cookie----->"+cookieString.get(0).getValue()); byte[] bytes = EntityUtils.toByteArray(httpResponse.getEntity()); bitmap=BitmapFactory.decodeByteArray(bytes, 0, bytes.length); // String htmlstr=EntityUtils.toString(httpResponse.getEntity()); // System.out.println("这是验证码页面的内容------>"+bytes); myhandler.sendEmptyMessage(1); } /** * 线程 * @author Administrator * */ private class Myhandler extends Handler{ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: new GetCodeThread().start(); break; case 1: String string=cookieString.get(0).getValue(); textView.setText(string); imageView.setImageBitmap(bitmap);

			break;
		case 2:
			if (!successed) {
				new GetCodeThread().start();
			}
			textView.setText(res);
			break;
		default:
			break;
		}
	}
}
@Override
public void onClick(View v) {
	new PostThread().start();
}

private class PostThread extends Thread {
	@Override
	public void run() {
		super.run();
		try {
			post();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
/**
 * 请求页面
 * @throws IOException 
 * @throws ClientProtocolException 
 * @throws Exception
 */
public void post() throws Exception {
	
	HttpPost httpPost  = new HttpPost("http://jwxt.tit.edu.cn/_data/index_LOGIN.aspx");
	httpPost.setHeader("Host", "jwxt.tit.edu.cn");
	httpPost.setHeader("Cookie","ASP.NET_SessionId="+cookieString.get(0).getValue());
	httpPost.setHeader("Connection","keep-alive");
	System.out.println("这是要加入到请求头里面的cookie----->"+cookieString.get(0).getValue());
	httpPost.setHeader("Referer", "http://jwxt.tit.edu.cn/_data/index_LOGIN.aspx");
	httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
	HashMap<String, String> parmas = new HashMap<String, String>();
	//parmas.put("__VIEWSTATE", viewstate);
	// 账号 密码 验证码  还有登陆类型		
	parmas.put("txt_asmcdefsddsd", name.getText().toString());
	parmas.put("txt_pewerwedsdfsdff", psw.getText().toString());
	parmas.put("txt_sdertfgsadscxcadsads", code.getText().toString());
	parmas.put("dsdsdsdsdxcxdfgfg","3FBCD2CE05FA3E3AB9E061D7CFD80D");
	//parmas.put("typeName","学生");
	parmas.put("Sel_Type","STU");
	//封装请求参数
	List<NameValuePair> pairs = new ArrayList<NameValuePair>();
	     if(parmas != null){
	         Set<String> keys = parmas.keySet();
	         for(Iterator<String> i = keys.iterator(); i.hasNext();) {
	              String key = (String)i.next();
	              pairs.add(new BasicNameValuePair(key, parmas.get(key)));
	              httpPost.setEntity(new UrlEncodedFormEntity(pairs,"gb2312"));
	         }
	    }
     HttpResponse httpResponse = httpClient.execute(httpPost);
     res = EntityUtils.toString(httpResponse.getEntity());
     cookieString = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();
		System.out.println("这是第三次请求的cookie----->"+cookieString.get(0).getValue());
     System.out.println("这是请求返回的数据------>"+res);

// if (!res.contains("<span id="xhxm">")) { // res = "failed"; // successed=false; // }else { // res = res.split("<span id="xhxm">")[1]; // res = res.split(" ")[1]; // res = res.split("</span>")[0]; // successed=true; // } // myhandler.sendEmptyMessage(2); Log.i("mytest", res); } //public void post() throws Exception{ // URL url = new URL("http://jwgl.fjnu.edu.cn/default2.aspx"); // HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // conn.setReadTimeout(10000); // conn.setConnectTimeout(10000); // conn.setDoInput(true); // 允许输入流 // conn.setDoOutput(true); // 允许输出流 // conn.setUseCaches(false); // 不允许使用缓存 // conn.setInstanceFollowRedirects(true); // 重定向 // conn.setRequestMethod("POST"); // 请求方式 // conn.setRequestProperty("Charset", "gb2312"); // 设置编码 // conn.setRequestProperty("Connection", "keep-alive"); // conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // conn.setRequestProperty("Cookie", string); // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // // //当文件不为空,把文件包装并且上传 // DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); // StringBuffer sb = null; // String params = ""; // HashMap<String, String> param = new HashMap<String, String>(); // param.put("__VIEWSTATE", "dDwtMTg3MTM5OTI5MTs7PuycOpFrJBnexiR2pbs7D5CEeTi6"); // param.put("TextBox1", "106042011154"); // param.put("TextBox2", "3585095"); // param.put("TextBox3", code.getText().toString()); // conn.connect(); // // /*** // * 以下是用于上传参数 // */ // if (param != null && param.size() > 0) { // Iterator<String> it = param.keySet().iterator(); // while (it.hasNext()) { // sb = null; // sb = new StringBuffer(); // String key = it.next(); // String value = param.get(key); // String content = key+"="+value+"&"; // // params = sb.toString(); // dos.writeBytes(content); //// dos.flush(); // // } // } // InputStream input = conn.getInputStream(); // StringBuffer sb1 = new StringBuffer(); // int ss; // while ((ss = input.read()) != -1) { // sb1.append((char) ss); // } // res = sb1.toString(); // Log.i("mytest",res); // myhandler.sendEmptyMessage(1); //}

}



这是完整代码 ,好心人看下吧。如果需要测试+我q 1120832563

展开
收起
爱吃鱼的程序员 2020-06-01 10:26:42 701 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    我不懂java代码,到我知道原因。因为你两次请求的sessionid不一样,你应该把第一次请求的sessionid保存下来,第二次请求的时候带上第一次的sessionid######@郭蕾 哦,那我就不知道了,看不懂java代码,不知道问题在哪。我第一次做验证码识别并登录的时候就是没注意sessionid问题,才折腾了很久^_^######谢谢你的回答,但是我的sessionid确实是加了的 httpPost.setHeader("Cookie","ASP.NET_SessionId="+cookieString.get(0).getValue()); 这个就是将sessionid加入到请求头里面。。。######代码有2个疑问 1. 为啥要自己控制cookie httpclient 会自己根据响应头控制 cookie 添加,移除 2. 在请求第2次时候会不会服务端有给你添加了一个 cookie 但是你还在取第一个。导致取出来的不一致了。######我在请求头里面加入cookie的目的 是为了跟踪会话!!!但是我那样加上 却没有跟踪到会话 怎么回事######这个 cookie 的添加和移除 httpclient 会帮你完成的额。 你把 httpclient 理解为你的浏览器就对了。 你是用浏览器你关心过 cookie 的吗?? 还有就是保证你没有重复的 new httpclient 不让这样会认为打开了两个浏览器。貌似处理cookie 这里不太一样了啊!! 哈哈扯多了

    2020-06-01 10:26:44
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载