从javascript获取调用无法访问java REST服务

时间:2017-05-21 02:20:46

标签: javascript json rest post fetch

我正在学习REST API并尝试使用fetch从Javascript调用用java编写的POST服务。当@Produces和@Consumes是MediaType.APPLICATION_JSON

时,请求未到达服务

我还在同一个API中定义了其他简单的POST和GET方法,这些方法工作正常但我必须发送和接收JSON数据的情况不起作用。

以下是我的提取电话:

 @Path("/data")
 public class Controller {
 @POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/list")
public Response createList(CreateListJsonData dta) throws IOException {
System.out.println("in create list");
return Response.status(200)
            .entity("{\"dummykey\"}:\"dummyVal\"")
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
            .build();
}

以下是我的REST API:

 @XmlRootElement
 public class CreateListJsonData {
    private String Title;
    public String getTitle() {
        return Title;
    }
    public void setTitle(String title) {
        Title = title;
    }
 }

CreateListJsonData类如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>myserver</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.myserver</param-value>
    </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

的web.xml:

 com.sun.jersey.server.wadl.generators.AbstractWadlGeneratorGrammarGenerator attachTypes
 INFO: Couldn't find grammar element for class javax.ws.rs.core.Response

我在eclipse上运行tomcat上的API。当我触发请求时,我会在控制台上收到消息:

public class LoginActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Students students = new Students();
        students.setID(1234);
        students.setFirstName("hello");
        Log.d("test", "pre students="+students);
        saveStudent(students);

        Students s = readStudent();
        Log.d("test", "after students="+s);

    }

    String fileName = "data.bin";

    public Boolean saveStudent(Students s) {//saves student into fileName (data.bin)
        ObjectOutputStream oos = null;
        try {
           /* File file = new File(this.getFilesDir().toString(), fileName);
            file.createNewFile();
            if(!file.mkdir()){ //just to check whats the reason behind the failed attempt
                Toast.makeText(this, "Security Issue", Toast.LENGTH_SHORT).show();
            }*/
            FileOutputStream fos = this.openFileOutput(fileName, this.MODE_PRIVATE);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(s);
            oos.close();
            fos.close();
            return true;
        } catch (FileNotFoundException err) {
            Toast.makeText(this, "Something went wrong while saving", Toast.LENGTH_SHORT).show();
            return false;
        } catch (Exception abcd) {
            Toast.makeText(this, "Ooops, I don't know what's the problem. Sorry about that!", Toast.LENGTH_SHORT).show();
            return false;
        }
        finally {//makes sure to close the ObjectOutputStream
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public Students readStudent() {//reads Student object from(data.bin) and returns it.
        ObjectInputStream ois = null;
        Students students = new Students();
        try {
            /*ois = new ObjectInputStream(new FileInputStream("data.bin"));*/
            ois = new ObjectInputStream(openFileInput(fileName));
            students = (Students) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return students;
    }
}

有人可以帮我解决我的错误吗?

1 个答案:

答案 0 :(得分:1)

这看起来像是一个跨域的情况,CORS

使用此内容类型,请求不再是“简单”,而是Preflighted request。它要求您的服务器处理OPTIONS方法(除了您处理的POST)。有关它需要返回的标头,请参阅链接的文章。通常,这样的事情:

Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Allow-Origin: *