繁体   English   中英

使用HttpClient将URL中的JSON查询字符串发送到Web服务(Java)

[英]Using HttpClient to send JSON query string in a URL to a web service (Java)

我有一个构建的Web服务...我现在要做的是将一个简单请求(其中包含一个Tapestry Web应用程序的json查询字符串)发送到该Web服务。 我到处搜索,大多数人说要使用Apache HttpClient来实现这一目标。 与HttpClient一起使用URIBuilder。

我尝试发送的Json对象看起来像这样

{“ user”:{“ userEmail”:“ jdoe@gmail.com”,“ firstName”:“ John”,“ lastName”:“ Doe”,“ phone”:“ 203- 555-5555”},“ password” :“死”}

*我意识到以纯文本等方式发送密码的问题...

可用的网址(通过手动输入网络浏览器进行测试,并且该网络服务已为Android客户端和iOS客户端提供服务)

http:// ##。##。###。## / createuser?json = {“ user”:{“ userEmail”:“ jdoe@gmail.com”,“ firstName”:“ John”,“ lastName” :“ Doe”,“ phone”:“ 203-555-5555”},“ password”:“ dead”}

这是我从谷歌那里拼凑在一起的HttpClient代码,试图弄清楚为什么它不起作用。 本质上,我想做的是使用URIBuilder创建URI,然后使用新建的URI构造HttpPost或HttpGet对象。 但是在URIBuilding过程中出了点问题。 调试时,尝试设置URI的所有方面时都会引发异常。

Object onSuccess() throws ClientProtocolException, IOException, URISyntaxException{
    // json = {"user":{"userEmail":"jdoe@gmail.com","firstName":"John","lastName":"Doe","phone":"203- 555-5555"},"password":"dead"}
    String json = user.toJson();
    URIBuilder builder = new URIBuilder();
    // Error gets thrown when I step over the next line
    builder.setScheme("http").setHost("##.###.##.###").setPort(8080).setPath("createuser").setQuery("json=" +json); 
    URI uri = builder.build();

    HttpPost request = new HttpPost(uri);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    String tmp = request.getURI().toString();

    HttpResponse response = httpClient.execute(request); 
    index.setResponse(EntityUtils.toString(response.getEntity()));
    return index;

当我越过代码中注释的行时返回的错误是

[错误] TapestryModule.RequestExceptionHandler处理请求失败,出现未捕获的异常:org.apache.http.client.utils.URLEncodedUtils.parse(Ljava / lang / String; Ljava / nio / charset / Charset;)Ljava / util / List; java.lang.NoSuchMethodError:org.apache.http.client.utils.URLEncodedUtils.parse(Ljava / lang / String; Ljava / nio / charset / Charset;)Ljava / util / List;

我已经尝试了许多其他方法和对象的组合,以使此请求正确发送到服务器,但似乎没有任何效果。 希望我能忽略一些相对简单的事情。

在此先感谢您提供的任何指导。

您很可能在类路径上使用了错误的一两个版本的apache httpcomponents。 如果您正在运行Tapestry,它将在错误页面上的类路径上打印出所有软件包。 在此处进行调查,找到要加载的httpcomponents,找出它的来源并进行修复。

如果这不起作用,则应与我们共享一些运行时环境。 哪个servlet引擎,从哪个IDE运行,或者从命令行运行。 您在使用Maven吗? 如果是这样,请分享您的pom。 等等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM