Java下载文本文件导致html代码而不是文本

时间:2015-07-10 13:52:45

标签: java

当我下载此文本文件asdf.txt时 使用apache commons-io:

URL fileURL = new URL(urlMatcher.group(1)); FileUtils.copyURLToFile(fileURL, new File(fileName));

它导致网页的html代码而不是

  

我是文本文件!

它应该返回。

将字符串打印为字符串会产生以下结果:

  

https://alm.automic.com/jama/attachment/542/asdf.txt

请帮我弄清楚登录所需的POST请求的Java代码

  

主机= alm.automic.com

     

User-Agent = Mozilla / 5.0(Windows NT 6.1; WOW64; rv:39.0)Gecko / 20100101 Firefox / 39.0

     

接受= text / html的,应用/ XHTML + xml的,应用/ XML; Q = 0.9, / 的; Q = 0.8

     

接受语言= EN-US,EN; Q = 0.5

     

Accept-Encoding = gzip,deflate

     

的Referer = https://alm.automic.com/jama/login.req

     

曲奇= JSESSIONID = CA14239217D0E54E913D17083F71724F; DWRSESSIONID = 8nCO $ BHWFA2282XF4fVYnmwl7Wk; jamaContourServerTime = 1436778397165; jamaContourSessionExpiry = 1436778397165

     

连接=保活

     

的Content-Type =应用程序/ x-WWW窗体-urlencoded

     

的Content-Length = 53

     

POSTDATA =为j_username =用户安培;为j_password = PASS&安培;提交=登录

请提前帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

如果有人需要,可以找到如何进行http连接: 使用以下类和Temper Data(Firefox插件)之类的东西来查找GET / POST请求标题/数据,并以类似这样的方式将其添加到以下类中。

ArrayList<String> cookies = new ArrayList<String>(1);
        HttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(link);

        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>(2);
        httpGet.addHeader("Host", "alm.automic.com");
        httpGet.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");
        httpGet.addHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpGet.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpGet.addHeader("Accept-Encoding", "gzip, deflate");
        if (cookies.size() > 1)
            httpGet.addHeader("Cookie",
                    cookies.get(cookies.size() - 1).split(";")[0]);
        httpGet.addHeader("Connection", "keep-alive");

        // Execute and get the response.
        HttpResponse response = httpclient.execute(httpGet);
        Header[] responseHeaders = response.getAllHeaders();
        String location = "https://alm.automic.com/jama/login.req;";

        for (int i = 0; i < responseHeaders.length; i++)
        {
            if (responseHeaders[i].getName().equals("Set-Cookie"))
            {
                if (responseHeaders[i].getValue().split(";")[0].split("=")[0]
                        .equals("JSESSIONID"))
                    cookies.add(responseHeaders[i].getValue());
            }
            if (responseHeaders[i].getName().equals("Location"))
            {
                location = responseHeaders[i].getValue();
            }
        }