java HttpsURLConnection 和 POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4376405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:05:34  来源:igfitidea点击:

HttpsURLConnection and POST

javapython

提问by kaharas

some time ago i wrote this program in python, that logged in a website using https, took some info and logged out. The program was quite simple:

前段时间我用 python 编写了这个程序,它使用 https 登录了一个网站,获取了一些信息并注销了。该程序非常简单:

class Richiesta(object):

def __init__(self,url,data):
    self.url = url
    self.data = ""
    self.content = ""
    for k, v in data.iteritems():
        self.data += str(k)+"="+str(v)+"&"
    if(self.data == ""):
        self.req = urllib2.Request(self.url)
    else:
        self.req = urllib2.Request(self.url,self.data)
    self.req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 5.1; rv:2.0b6) Gecko/20100101 Firefox/4.0b6')
    self.req.add_header('Referer', baseurl+'/www/')
    self.req.add_header('Cookie', cookie )

def leggi(self):
    while(self.content == ""):
        try:
            r = urllib2.urlopen(self.req)
        except urllib2.HTTPError, e:
            print("Errore del server, nuovo tentativo tra 15 secondi")
            time.sleep(15)                
        except urllib2.URLError, e:
            print("Problema di rete, proverò a riconnettermi tra 20 secondi")
            time.sleep(20)
        else:
                self.content = r.read().decode('utf-8')
def login(username,password):
    global cookie
    print("Inizio la procedura di login")
    url = "https://example.com/auth/Authenticate"
    data = {"login":"1","username":username,"password":password}
    f = Richiesta(url,data)
    f.leggi() 

Now, for some reason, I have to translate it in java. Untill now, this is what i've writte:

现在,出于某种原因,我必须用 Java 翻译它。直到现在,这就是我所写的:

import java.net.*;
import java.security.Security.*;
import java.io.*;
import javax.net.ssl.*;

public class SafeReq {
    String baseurl = "http://www.example.com";
    String useragent = "Mozilla/5.0 (Windows NT 5.1; rv:2.0b6) Gecko/20100101 Firefox/4.0b6";
    String content = "";

    public SafeReq(String s, String sid, String data) throws MalformedURLException {
        try{
            URL url = new URL(s);
            HttpsURLConnection request = ( HttpsURLConnection ) url.openConnection();

            request.setUseCaches(false);
            request.setDoOutput(true);
            request.setDoInput(true);

            request.setFollowRedirects(true);
            request.setInstanceFollowRedirects(true);

            request.setRequestProperty("User-Agent",useragent);
            request.setRequestProperty("Referer","http://www.example.com/www/");
            request.setRequestProperty("Cookie","sid="+sid);
            request.setRequestProperty("Origin","http://www.example.com");
            request.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            request.setRequestProperty("Content-length",String.valueOf(data.length()));

            request.setRequestMethod("POST");
            OutputStreamWriter post = new OutputStreamWriter(request.getOutputStream());
            post.write(data);
            post.flush();

            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                content += inputLine;
            }
            post.close();
            in.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public String leggi(){
        return content;
    }
}

The problem is, the login doesn't work, and when i try to get a page that require me to be logged, i get the "Login Again" message. The two classes seems quite the same, and i can't understand why i can't make the second one to work ... any idea?

问题是,登录不起作用,当我尝试获取需要我登录的页面时,我收到“再次登录”消息。这两个班级似乎完全相同,我不明白为什么我不能让第二个班级工作......知道吗?

回答by Neeme Praks

Where do you get your sidfrom? From the symptoms, I would guess that your session cookie is not passed correctly to the server.

sid从哪里得到你的?从症状来看,我猜您的会话 cookie 没有正确传递到服务器

See this question for possible solution: Cookies turned off with Java URLConnection.

请参阅此问题以获取可能的解决方案:使用 Java URLConnection 关闭 Cookies

In general, I recommend you to use HttpClientfor implementing HTTP conversations in Java(anything more complicated than a simple one-time GET or POST). See code examples(I guess "Form based logon" example is appropriate in your case).

通常,我建议您使用HttpClient在 Java 中实现 HTTP 对话(任何比简单的一次性 GET 或 POST 更复杂的东西)。请参阅代码示例(我猜“基于表单的登录”示例适合您的情况)。

回答by cbaldan

Anyone looking for this in the future, take a look at HtmlUnit. This answerhas a nice example.

任何人在未来寻找这个,看看HtmlUnit。这个答案有一个很好的例子。