从网址下载文件

时间:2015-05-20 13:44:55

标签: java rest cron

我想在cron选项卡中添加一个调度作业,就像使用url的GET请求一样。我在我的restful应用程序中为该端点编写了以下代码,以便从给定的URL执行某些xml文件的下载。我发现需要用户交互才能选择保存或从弹出框中打开。我希望在没有cron调度程序的任何用户交互的情况下自动完成作业。

import java.io.File;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

@Path("/metadata-management")
public class FileService {

private static final String FILE_PATH = "c:\\file.log";

@GET
@Path("/get")
@Produces("text/plain")
public Response getFile() {

    File file = new File(FILE_PATH);

    ResponseBuilder response = Response.ok((Object) file);
    response.header("Content-Disposition",
        "attachment; filename=\"file_from_server.log\"");
    return response.build();

}

}

我是否应该使用HttpURLConnection从HTTP URL下载文件,而不是在上面的代码块中下载文件并返回null以进行响应?

2 个答案:

答案 0 :(得分:0)

试试这个:

public static String loadXml(String url) {
     HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
     System.setProperty("http.agent", "");
     con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
     con.setRequestMethod("GET");
     con.setDoInput(true);
     con.setDoOutput(true);
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     int n;
     while (( n =con.getInputStream().read())!=-1) {
         baos.write(n);
     };

     con.disconnect();
     return new String(baos.toByteArray(),"UTF-8");
}

答案 1 :(得分:0)

使用 if (_Touches.Length == 2) { Vector2 _CameraViewsize = new Vector2(_Camera.pixelWidth, _Camera.pixelHeight); Touch _TouchOne = _Touches[0]; Touch _TouchTwo = _Touches[1]; Vector2 _TouchOnePrevPos = _TouchOne.position - _TouchOne.deltaPosition; Vector2 _TouchTwoPrevPos = _TouchTwo.position - _TouchTwo.deltaPosition; float _PrevTouchDeltaMag = (_TouchOnePrevPos - _TouchTwoPrevPos).magnitude; float _TouchDeltaMag = (_TouchOne.position - _TouchTwo.position).magnitude; float _DeltaMagDiff = _PrevTouchDeltaMag - _TouchDeltaMag; _Camera.transform.position += _Camera.transform.TransformDirection((_TouchOnePrevPos + _TouchTwoPrevPos - _CameraViewsize) * _Camera.orthographicSize / _CameraViewsize.y); _Camera.orthographicSize += _DeltaMagDiff * _OrthoZoomSpeed; _Camera.orthographicSize = Mathf.Clamp(_Camera.orthographicSize, _MinZoom, _MaxZoom) - 0.001f; _Camera.transform.position -= _Camera.transform.TransformDirection((_TouchOne.position + _TouchTwo.position - _CameraViewsize) * _Camera.orthographicSize / _CameraViewsize.y); } 方法,您可以根据需要创建URL.getInputStream(),并将所有数据读取为字符串。然后,使用BufferedReader将其写入文件。使用此代码:

BufferedWriter