问题
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.
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>
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?
Thanks in advance for you help.
回答1:
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.
For a GET request, you can either pass the information as segments in the url or as querystring parameters.
As segments in the url:
/resourcetype/{path}/{filename}
http://testserver:8080/resourcetype/test/2/2/test.jpg
As querystring params:
/resourcetype?path={path}&file={filename}
http://testserver:8080/resourcetype?path=test/2/2&filename=test.jpg
来源:https://stackoverflow.com/questions/13944458/how-to-send-a-get-request-with-a-in-the-query