【问题标题】:How can I pass a URL from Javascript to Java module如何将 URL 从 Javascript 传递到 Java 模块
【发布时间】:2016-05-28 07:07:51
【问题描述】:

每当用户点击 chrome 扩展时,我想将 URL 字符串发送到 java 模块。

这是我的 JS 代码

document.addEventListener('DOMContentLoaded', function () {

      chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
      alert(tabs[0].url)
      var http = new XMLHttpRequest();
        var someValue = "http://chums/chummi";

        var url = "http://localhost:8080/SalesRESTservice/apicall/restcall2/";

        http.open("GET", url, true);

        http.setRequestHeader("Content-type", "application/json; charset=utf-8");
        http.setRequestHeader("Content-length", params.length);
        http.setRequestHeader("Connection", "close");

        http.send(someValue);
    });
  });

这是我的 Java

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.json.JSONException;
import org.json.JSONObject;

@Path("/restcall2")
public class restcall2 {


      @Path("{f}")
      @GET
      @Produces("text/plain")
      public Response RESTcall(@PathParam("f") String f) throws JSONException {
        return Response.status(200).entity(f).build();
      }

}

每当我尝试点击 URL http://localhost:8080/SalesRESTservice/apicall/restcall2/ 我没有得到回应。 在我的网络选项卡中,它显示

我正在使用 Tomcat 服务器来处理请求

【问题讨论】:

  • 不知道为什么会收到 405 错误代码

标签: javascript java rest


【解决方案1】:

405 - 不允许的方法

您的服务器没有监听该 url。

也试试 GET /restcall2/somevalue

检查您的部署配置和服务器日志。根据提供的信息,无法猜测服务器部分发生了什么故障

关于一般项目:。您应该将 GET 更改为 POST 以避免 URL 编码问题

http.send(someValue) 用于 POST 请求

如果不使用 json,请不要使用编码 aplicación/json。例如,您可以使用

POST /restcall2 应用程序/x-www-form-urlencoded myurl=someValue

在服务器部分

   @POST
@Path("/")
public Response RESTcall(
    @FormParam("myurl") String url

【讨论】:

    【解决方案2】:

    问题出在你的 Java 端 尝试更改您的 java 代码

    • 使用帖子
    • 避免路径参数 & 删除@path{f},这将确保没有其他 值不会命中 URL

      import javax.ws.rs.GET;
      @Path("/restcall2")
      public class restcall2 {      
        @POST
        @Produces("text/plain")
        public Response RESTcall(String f) throws JSONException {
            System.out.println(f);
          return Response.status(200).entity("hello " + f).build();
        }
      

      }

    【讨论】:

      猜你喜欢
      • 2017-01-27
      • 1970-01-01
      • 2017-11-10
      • 2012-03-29
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      相关资源
      最近更新 更多