【发布时间】:2015-09-08 17:01:21
【问题描述】:
我尝试使用HttpClient(4.3)OAuth 登录 Instagram,但收到以下错误消息:
无法加载此页面。如果您在您的 浏览器,或者您正在以隐私模式浏览,请尝试启用 cookie 或关闭隐私模式,然后重试您的操作。
我花了三天时间尝试了所有可以在post请求中设置cookie的方法,但我仍然没有解决这个问题!
谁能帮帮我?
我的操作步骤:
1. Get login page with HttpGet.
2. Parse Cookie from response.
3. Parse form action from response.
4. Parse form fields from response.
5. Set Cookie to HttpPost.
6. Set form fields to HttpPost.
7. Post the form.
8. Get the error message.
代码:
-
Init HttpClient:RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build(); CookieStore cookieStore = new BasicCookieStore(); HttpClientContext context = HttpClientContext.create(); context.setCookieStore(cookieStore); CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build(); -
发送获取登录页面请求:
HttpGet get = new HttpGet(url); get.setHeader( "User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); HttpResponse response = httpClient.execute(get); -
获取 Cookie:
private Map<String, String> getCookies(HttpResponse response) { Map<String, String> cookieMap = new HashMap<String, String>(); Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName().equals("Set-Cookie")) { String cookie = headers[i].getValue(); String[] pairs = cookie.split(";"); for(String pair: pairs){ String[] keyValue = pair.split("="); String cookieName = keyValue[0]; String cookieValue = keyValue[1]; cookieMap.put(cookieName, cookieValue); } } } return cookieMap; } -
获取表单字段:
// org.htmlparser.Parser private static Map<String, String> getFormFields(NodeList list, String keyword) { Map<String, String> responeMap = new HashMap<String, String>(); SimpleNodeIterator iterator = list.elements(); while (iterator.hasMoreNodes()) { Node node = iterator.nextNode(); NodeList childList = node.getChildren(); if (null == childList) { if (node instanceof InputTag) { InputTag d = (InputTag) node; if (d.getAttribute("name") != null) responeMap.put(d.getAttribute("name"), d.getAttribute("value")); } } else { if(node instanceof FormTag){ FormTag d = (FormTag)node; loginAction = d.getAttribute("action"); } responeMap.putAll(processNodeList(childList, keyword)); } } return responeMap; } -
发帖形式:
HttpPost post = new HttpPost(loginUrl); post.setHeader( "User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); if (cookieMap.size() > 0) { post.setHeader("Cookie", buildCookies(cookieMap)); } UrlEncodedFormEntity uef = new UrlEncodedFormEntity(pairs, "UTF-8"); post.setEntity(uef); response = httpClient.execute(post); 获取错误信息
无法加载此页面。如果您在您的 浏览器,或者您正在以隐私模式浏览,请尝试启用 cookie 或关闭隐私模式,然后重试您的操作。
【问题讨论】:
标签: java login oauth-2.0 httpclient instagram-api