2015-06-11 46 views
3

我正在尝试使用一个流行的俄罗斯社交网络的api。我通过Java HttpUrlConnection使用OAuth。问题是,当我通过Java发送发布数据时,我得到了401个响应代码。当我复制请求并将其粘贴到浏览器时,我将重定向到包含我需要的访问令牌的URL。这意味着我的发布请求是正确的,但为什么当我用Java发送它时,我得到401错误?当我用不正确的密码发送请求时,我得到200.这意味着请求也是正确的。Java Post请求和浏览器发布请求之间的区别

private void getHomeAuth() throws Exception { 
     String url = "https://oauth.vk.com/authorize?client_id=APP_ID&scope=friends&redirect_uri=https://oauth.vk.com/blank.html&display=page&v=5.34&response_type=token"; 

     URL oauth = new URL(url); 
     HttpURLConnection connection = (HttpURLConnection) oauth.openConnection(); 
     connection.setRequestMethod("GET"); 
     connection.setRequestProperty("User-Agent", USER_AGENT); 
     int responseCode = connection.getResponseCode(); 
     System.out.println("Response code: " + responseCode); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
     String inputLine; 
     StringBuilder response = new StringBuilder(); 

     while((inputLine = reader.readLine()) != null) 
      response.append(inputLine + "\n"); 
     reader.close(); 
     PrintWriter writer = new PrintWriter("auth.html"); 
     writer.print(response); 
     writer.close(); 
     parse(); 
     cookies = connection.getHeaderField("Set-Cookie"); 
     referer = connection.getURL().toString(); 
    } 



private void postAuth() throws Exception { 
     email = URLEncoder.encode("[email protected]", "UTF-8"); 
     password = "password"; 
     _origin = URLEncoder.encode(_origin, "UTF-8"); 
     String url = "https://login.vk.com/?act=login&soft=1"; 
     URL post = new URL(url); 
     String urlParameters = "ip_h=" + ip_h + "&_origin=" + _origin + "&to=" + to + "&expire=" + expire + "&email=" + email + "&pass=" + password; 
     HttpsURLConnection con = (HttpsURLConnection) post.openConnection(); 
     con.setRequestMethod("POST"); 
     con.setRequestProperty("User-Agent", USER_AGENT); 
     con.setRequestProperty("Cookie", cookies); 
     con.setDoOutput(true); 
     DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
     wr.writeBytes(urlParameters); 
     wr.flush(); 
     wr.close(); 
     int responseCode = con.getResponseCode(); 



     System.out.println("Sent post. Response code: " + responseCode + "\nRequest: " + post.toString() + urlParameters + "\nRequestMethod: " + con.getRequestMethod()); 

    } 

我也尝试通过浏览器中的插件发送此请求,结果是正确的。我从重定向链接获得访问令牌。

也许问题是请求内的东西是不正确的。我试图监控来自Java应用程序的请求,但我失败了。

+0

也许该网站会检查[Referer](https://en.wikipedia.org/wiki/HTTP_referer)或某种[XSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery #Prevention)令牌? – bratkartoffel

+0

不幸的是,添加Referer并不能解决问题。事实上,我甚至试图通过使用TamperData来完成一个请求的完整副本,但它不起作用。 – starwars25

回答

1

我对这种问题的经验是,首先认证用户的http请求也会将cookies(范围因案例而异)放入响应中,并且随后的http请求应包含这些cookie。仔细查看完整的返回响应标题,以查看可能已返回的cookie。