如何发送带有"/"的GET请求.在查询中 [英] How to send a GET request with a "/" in the query

查看:73
本文介绍了如何发送带有"/"的GET请求.在查询中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个测试程序来测试我的Web服务.我正在通过GET方法将JSON对象发送到我的Web服务,但是它不起作用.我的测试网址如下:

I'm trying to write a test program to test my web service. I'm sending a JSON object to my web service via the GET method but it's not working. My test URL looks like this:

http://testserver:8080/mydir/{"filename":"test.jpg", "Path":"test/2/2"}

我认为路径中的"/"正导致我出现问题,因为一旦删除它们,程序就可以正常工作.

I'm thinking the "/" in the path are causing me problems since the program works fine once I remove them.

每个 REST如何通过包含"/"的值作为URI中的路径参数?,我尝试使用java.net.URLEncoder.encode,但这无济于事.这是我的测试程序的片段:

Per REST how to pass values containing "/" as path parameter in the URI?, I've tried to use java.net.URLEncoder.encode but that isn't helping. Here's a snippet of my test program:

// some code from main method
<snip snip>
String url = "http://testserver:8080/mydir/";
String JSON = "{\"filename\":\"test.jpg\",\"Path\":\"test/2/2\"}";
String enc_JSON = URLEncoder.encode(JSON,"UTF-8");
String testGet = url + enc_JSON;
String out2 = TestCode.httpGet(testGet);
<snip snip>

// code from httpGet method
public static String httpGet(String serverURL) {
  URL url;
  HttpURLConnection conn;

  try {
      url = new URL (serverURL);
      conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setUseCaches(false);
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.connect();
// failing at line below
      InputStream input = conn.getInputStream();
<snip snip>

我的程序的结果是我得到一个HTTP响应代码:400.我是否忘记在httpGet()方法的代码中添加了某些内容,导致其失败,或者由于JSON对象是否在路径位置末尾加上"/"?

The result of my program is I get an HTTP response code: 400. Did I forget to add something in my code in the httpGet() method that's causing it to fail or am I doing something illegal in my URL due to the JSON object being tacked on at the end with the "/" in the path location?

预先感谢您的帮助.

推荐答案

对于REST API,通常在请求的正文中发送(POST)或返回JSON对象.它们通常不编码为URL的一部分.

For REST APIs, JSON objects are typically sent (POST) or returned in the body of the request. They are not typically encoded as part of the URL.

对于GET请求,您可以将信息作为url中的段传递,也可以作为querystring参数传递.

For a GET request, you can either pass the information as segments in the url or as querystring parameters.

作为网址中的细分:

/resourcetype/{path}/{filename}
http://testserver:8080/resourcetype/test/2/2/test.jpg

作为查询字符串参数:

/resourcetype?path={path}&file={filename}
http://testserver:8080/resourcetype?path=test/2/2&filename=test.jpg

这篇关于如何发送带有"/"的GET请求.在查询中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆