3
回答
httpclient 登录遇到问题 请各位大大帮我看一下
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Lookup;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.DefaultCookieSpecProvider;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


public class Test {
static final String admin5 = "http://lm.admin5.com";
static final String loginURL = "http://lm.admin5.com/index.login";

public static void main(String[] args) throws IOException  {
String list302 ="http://lm.admin5.com";
//http://lm.admin5.com/index.login
//http://lm.admin5.com/index.postlogin


//创建一个HttpClient
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

HttpGet getlogin = new HttpGet(loginURL);

try {
CloseableHttpResponse loginResponse = httpClient.execute(getlogin);
String PHPSESSID = loginResponse.getFirstHeader("Set-Cookie").getValue();
String sessid=PHPSESSID.substring(PHPSESSID.indexOf("PHPSESSID"), PHPSESSID.indexOf(";"));
System.out.println(sessid);

loginResponse.close();
//构造POST数据
List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();
valuePairs.add(new BasicNameValuePair("username", "账号XXXXXXXXXXX"));
valuePairs.add(new BasicNameValuePair("password", "密码XXXXXXXXXX"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
HttpPost postlogin = new HttpPost("http://lm.admin5.com/adv/ad.edit/adsid-12004");
postlogin.setHeader("Cookie", PHPSESSID);
postlogin.setEntity(entity);


CloseableHttpResponse postResponse = httpClient.execute(postlogin);
//	String responseHtml = EntityUtils.toString();
if(postResponse.getStatusLine().getStatusCode()==302){
//list302 = list302+postResponse.getFirstHeader("Location").getValue();
}
postResponse.close();
System.out.println(list302);


} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
httpClient.close();
}
}
}




举报
顶部