1public class LoginTo
2{
3
4
5 public static void main(String[] args) throws Exception {
6
7 HttpClient httpClient=new HttpClient();
8 String url = "http://passport.baidu.com/?login&tpl=sp&tpl_reg=sp";
9 PostMethod postMethod = new PostMethod(url);
10// 填入各个表单域的值
11 NameValuePair[] data = { new NameValuePair("username", "username"),
12 new NameValuePair("password", "password") };
13// 将表单的值放入postMethod中
14 postMethod.setRequestBody(data);
15// 执行postMethod
16 int statusCode = httpClient.executeMethod(postMethod);
17// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
18// 301或者302
19 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
20 statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
21 // 从头中取出转向的地址
22 Header locationHeader = postMethod.getResponseHeader("location");
23 String location = null;
24 if (locationHeader != null) {
25 location = locationHeader.getValue();
26 System.out.println("The page was redirected to:" + location);
27 postMethod.releaseConnection();
28
29 GetMethod get=new GetMethod("http://passport.baidu.com/"+location);
30 statusCode = httpClient.executeMethod(get);
31 System.out.print(get.getStatusText());
32 if (statusCode != HttpStatus.SC_OK) {
33 System.err.println("Method failed: " + get.getStatusLine());
34 }else{
35 /**//*
36 InputStreamReader isr=new InputStreamReader(get.getResponseBodyAsStream(),"GBK");
37 int d=0;
38 while((d=isr.read())!=-1){
39 System.out.print((char)d);
40 }
41 //成功登陆了百度
42
43 */
44 get.releaseConnection();
45 ////////////////////////////进行发布文章
46 postMethod=new PostMethod("http://hi.baidu.com/amushen/commit");
47 NameValuePair[] data1={new NameValuePair("ct","1"),
48 new NameValuePair("cm","1"),
49 new NameValuePair("spBlogTitle","testcharset"),
50 new NameValuePair("spBlogText",new String("测试汉字测试汉字".getBytes(),"GBK")),
51 new NameValuePair("spBlogCatName","Diary"),
52 new NameValuePair("spIsCmtAllow","0"),
53 new NameValuePair("spBlogPower","3")
54
55 };
56 postMethod.removeRequestHeader("Content-Type");
57 Header setHeader = new Header("Content-Type", "text/html; charset=GBK");
58 postMethod.addRequestHeader(setHeader);
59 postMethod.setRequestBody(data1);
60 httpClient.executeMethod(postMethod);
61 System.out.print("public:"+postMethod.getStatusLine());
62 System.out.println("|");
63 InputStreamReader isr=new InputStreamReader(postMethod.getResponseBodyAsStream(),"GBK");
64 int d=0;
65 while((d=isr.read())!=-1){
66 System.out.print((char)d);
67 }
68 postMethod.releaseConnection();
69
70
71
72
73 }
74
75
76 } else {
77 System.err.println("Location field value is null.");
78 }
79 return;
80 }
81
82 postMethod.releaseConnection();
83
84
85 }
86}
87
使用了httpclient组件。感觉好复杂啊