Jsf Java web应用程序尝试从API下载信息不工作

Jsf Java web应用程序尝试从API下载信息不工作,jsf,Jsf,我有一个用JSF制作的Java web应用程序,它连接到一个API,用信息填充一个数据表,每一行都有下载按钮。当我按下下载按钮时,它执行另一个get请求,id取自单击该按钮的行。但当我按下下载按钮时,我会收到以下消息: emptyResponse: An empty response was received from the server. Check server error logs. 服务器日志没有显示任何错误。 代码如下: package com.serban; import c

我有一个用JSF制作的Java web应用程序,它连接到一个API,用信息填充一个数据表,每一行都有下载按钮。当我按下下载按钮时,它执行另一个get请求,id取自单击该按钮的行。但当我按下下载按钮时,我会收到以下消息:

emptyResponse: An empty response was received from the server.  Check server error logs.
服务器日志没有显示任何错误。 代码如下:

package com.serban;

import com.google.common.io.ByteStreams;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import static java.lang.System.out;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipOutputStream;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

@ManagedBean(name = "logic", eager = true)
@SessionScoped
public class Logic implements Serializable {

static JSONObject jsonObject = null;
static JSONObject jo = null;
static JSONArray cat = null;

private ArrayList<Mesaj> logics;
StringBuilder sb = new StringBuilder();
String cif2;
String data_creare2;
String id_solicitare2;
String tip2;
String id2;
String detalii2;
String numar2;

/**
 *
 * @throws ParseException
 */

public void apelareApi()   {

  try {   
 URL url = new URL("xxx");
 URLConnection yc = url.openConnection();
 BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
 String inputLine;

 while((inputLine = in.readLine())!= null){
     System.out.println(inputLine);
     sb.append(inputLine+"\n");


 }

 in.close();




 }catch(Exception e) {System.out.println(e);}



}



public void incarcareLista() throws ParseException  {
    JSONParser parser = new JSONParser();

    jsonObject = (JSONObject) parser.parse(sb.toString());
    cat = (JSONArray) jsonObject.get("mesaje");
    logics = new ArrayList<Mesaj>();
        for(int i = 0; i < cat.size(); i++) {
    Mesaj m = new Mesaj();
    jo = (JSONObject) cat.get(i);
    cif2 = jo.get("cif").toString();
    data_creare2 = jo.get("data_creare").toString();
    id_solicitare2 = jo.get("id_solicitare").toString();
    tip2 = jo.get("tip").toString();
    id2 = jo.get("id").toString();
    detalii2 = jo.get("detalii").toString();
    numar2 = Integer.toString(i+1);
    m.setCif(cif2);
    m.setData_creare(data_creare2);
    m.setId_solicitare(id_solicitare2);
    m.setTip(tip2);
    m.setId(id2);
    m.setDetalii(detalii2);
    m.setNumar(numar2);
    logics.add(m);
}


}

/**
 *
 * @throws ParseException
 */
@PostConstruct
public void apelareSiIncarcare()  {
    apelareApi();
    try {
        incarcareLista();
    } catch (ParseException ex) {
        Logger.getLogger(Logic.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public ArrayList<Mesaj> getLogics() {
    return logics;
}

public Logic() {
}

String x;
String id;
byte[] rasp;
public void printNumar(String x) throws IOException  {


    this.x = x;
    //System.out.println(x);


    int y = Integer.parseInt(x);
    jo = (JSONObject) cat.get(y-1);
    System.out.println(jo.get("id"));
    id = jo.get("id").toString();



    rasp = apelareApi2(id);

    startDownload(rasp);



    }
byte[] byteChunk;
public byte[] apelareApi2(String z) throws IOException {


        URL url = new URL("xxx"+z);

        URLConnection yc = url.openConnection();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byteChunk = new byte[is.available()]; // Or whatever size you want to read in at a time.
int n;

while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
   }
   }
  catch (IOException e) {
  System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(),e.getMessage());e.printStackTrace ();}finally {
  if (is != null) { is.close(); }
  }
 return byteChunk;
    }



private void startDownload(byte[] continut)
        throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    // externalContext.responseReset();
    externalContext.setResponseHeader("Cache-Control", "public");
    externalContext.setResponseHeader("Pragma", "public");
    externalContext.setResponseHeader("Content-Type", "application/pdf");
    externalContext.setResponseHeader("Content-Length",
            Integer.toString(continut.length));
    externalContext.setResponseHeader("Content-Disposition",
            "attachment;filename=\"" + "id.pdf" + "\"");
    externalContext.getResponseOutputStream().write(continut);
    facesContext.responseComplete();
}


}
package com.serban;
导入com.google.common.io.ByteStreams;
导入com.itextpdf.text.BaseColor;
导入com.itextpdf.text.Chunk;
导入com.itextpdf.text.Document;
导入com.itextpdf.text.DocumentException;
导入com.itextpdf.text.Font;
导入com.itextpdf.text.FontFactory;
导入com.itextpdf.text.pdf.PdfWriter;
导入java.io.BufferedReader;
导入java.io.ByteArrayOutputStream;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.io.Serializable;
导入静态java.lang.System.out;
导入java.net.URL;
导入java.net.URLConnection;
导入java.util.ArrayList;
导入java.util.logging.Level;
导入java.util.logging.Logger;
导入java.util.zip.ZipoutStream;
导入javax.annotation.PostConstruct;
导入javax.faces.bean.ManagedBean;
导入javax.faces.bean.SessionScoped;
导入javax.faces.context.ExternalContext;
导入javax.faces.context.FacesContext;
导入javax.servlet.http.HttpServletResponse;
导入org.apache.commons.lang.StringUtils;
导入org.json.simple.JSONArray;
导入org.json.simple.JSONObject;
导入org.json.simple.parser.JSONParser;
导入org.json.simple.parser.ParseException;
@ManagedBean(name=“logic”,eager=true)
@会议范围
公共类逻辑实现可序列化{
静态JSONObject JSONObject=null;
静态JSONObject jo=null;
静态JSONArray cat=null;
私有数组列表逻辑;
StringBuilder sb=新的StringBuilder();
字符串cif2;
字符串数据_creare2;
字符串id_lakeare2;
字符串tip2;
字符串id2;
字符串detali2;
字符串numar2;
/**
*
*@ParseException
*/
公共无效apelareApi(){
试试{
URL=新URL(“xxx”);
URLConnection yc=url.openConnection();
BufferedReader in=新的BufferedReader(新的InputStreamReader(yc.getInputStream());
字符串输入线;
而((inputLine=in.readLine())!=null){
系统输出打印LN(输入线);
sb.追加(inputLine+“\n”);
}
in.close();
}catch(异常e){System.out.println(e);}
}
public void invocateLista()引发ParseException{
JSONParser=新的JSONParser();
jsonObject=(jsonObject)parser.parse(sb.toString());
cat=(JSONArray)jsonObject.get(“mesaje”);
logics=新的ArrayList();
对于(int i=0;i0){
写入(byteChunk,0,n);
}
}
捕获(IOE异常){
System.err.printf(“从%s:%s读取字节时失败”,url.toExternalForm(),e.getMessage();e.printStackTrace();}最后{
如果(is!=null){is.close();}
}
返回byteChunk;
}
私有void startDownload(字节[]continut)
抛出IOException{
FacesContext FacesContext=FacesContext.getCurrentInstance();
ExternalContext=facesContext.getExternalContext();
//externalContext.responseReset();
setResponseHeader(“缓存控制”、“公共”);
setResponseHeader(“Pragma”,“public”);
setResponseHeader(“内容类型”、“应用程序/pdf”);
setResponseHeader(“内容长度”,
整数.toString(continut.length));
setResponseHeader(“内容处置”,
“附件;文件名=\”“+”id.pdf“+”\”;
externalContext.getResponseOutputStream().write(continut);
facesContext.responseComplete();
}
}

如果收到一个AJAX响应,而该响应在
JSF uncompressed.js
中不包含XML,则Mojarra JSF会抛出错误消息:

 * Receive an Ajax response 
 * from the server.
 * Usage:
 * 
 * jsf.ajax.response(request, context);
 * 
 * Implementation Requirements:
 * This function must evaluate the markup returned in the
 * request.responseXML object and perform the following action:
 * 
 * If there is no XML response returned, signal an "emptyResponse"
 * error.

 ...

 } else if (status == "emptyResponse") {
    data.description = "An empty response was received from the server.  Check server error logs.";
这表明您正在使用AJAX。正如BalusC所述,JavaScript不允许在此处启动保存文档对话框:


因此,让您更进一步的解决方案是:关闭AJAX。

看起来您添加了问题中缺少的PDF内容部分。但这仍然不是一个问题,最小的相关UI部分看起来如何