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.
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
Related
I'm trying to send a video url in a http POST request but it's not working for me, I think I've (almost?) the necessary code to make it work, or else I'm missing something very simple?
public void postVideoURL() throws IOException {
String encodedUrl = URLEncoder.encode("http://video.ted.com/talks/podcast/DavidBrooks_2011.mp4", "UTF-8");
URL obj = new URL("http://10.50.0.105:8060/launch/dev?url="+encodedUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
// Send post request
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
System.out.println(con.getResponseCode());
System.out.println(con.getResponseMessage());
wr.flush();
wr.close();
wr.write("");
}
Any tips to lead me to the right direction?
Here is what I'm trying to do but in C#
using System.Net;
using System.Web;
class Program
{
static void Main()
{
string rokuIp = "192.168.0.6";
string channelId = "dev";
string videoUrl = "http://video.ted.com/talks/podcast/DavidBrooks_2011.mp4";
// Note that the query string parameters should be url-encoded
string requestUrl = $"http://{rokuIp}:8060/launch/{channelId}?url={HttpUtility.UrlEncode(videoUrl)}";
using (var wc = new WebClient())
{
// POST the query string with no data
wc.UploadString(requestUrl, "");
}
}
}
The following Post command to use in terminal works, this is essentially what I want to do, but in Java:
curl -d "" "http://10.50.0.46:8060/launch/12?url=http%3A%2F%2Fvideo.ted.com%2Ftalks%2Fpodcast%2FDavidBrooks_2011.mp4"
You are never writing anything to the output stream. You have to call wr.write() to write your data to the stream.
Also, you can't encode the URL like that inside the String. You need to concatenate the two Strings together after you've encoded the url separately. Like this:
String encodedUrl = URLEncoder.encode("http://video.ted.com/talks/podcast/DavidBrooks_2011.mp4");
URL obj = new URL("http://10.50.0.105:8060/launch/dev?url="+encodedUrl);
I am trying to send json data to Influx db using following code:
String url = "http://xx.x.xx.xx:8086/db/monitoring/check_1113?u=root&p=root";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
//String userpass = "user" + ":" + "pass";
//String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8"));
//conn.setRequestProperty ("Authorization", basicAuth);
//String data = "{\"format\":\"json\",\"pattern\":\"#\"}";
System.out.println("Data to send: "+"[{\"name\": \"check_222\",\"columns\": [\"time\", \"sequence_number\", \"value\"],\"points\": [["+unixTime+", 1, \"122\"]]}]");
String data = "[{\"name\": \"check_333\",\"columns\": [\"time\", \"sequence_number\", \"value\"],\"points\": [["+14444444444+", 1, \"122\"]]}]";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.close();
new InputStreamReader(conn.getInputStream());
System.out.println("Data Sent");
Where xx.xx.xx.xx is the ip of server where influx is deployed and i am using the Ip.
When i do a manual curl with this data (on localhost), the data is sent successfully. curl is provided below:
curl -X POST -d '[{"name": "check_223","columns": ["time", "sequence_number", "value"],"points": [[1445271004000,1,70.8880519867]]}]' 'http://localhost:8086/db/monitoring/series?u=root&p=root'
But when I run the code to send the data via the java program shared above, i get following error:
java.io.FileNotFoundException: http://xx.x.xx.xx:8086/db/monitoring/check_1113?u=root&p=root
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1834)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
at com.snapdeal.hadoop.monitoring.hdfs1.App.sendJsonDataToInflux(App.java:52)
at com.snapdeal.hadoop.monitoring.hdfs1.App.main(App.java:89)
[INFO - 2015-10-20T16:27:13.152Z] ShutdownReqHand - _handle - About to shutdown
And to add to it, I am using phantomJS to get the data from web page and pass that data in the JSON request. But for simplicity I have hard-coded it at present.
This should be relatively obvious. A 405 indicates that the HTTP Method on the request is not supported by the endpoint. The service you are calling does not support a PUT method.
I am invoking a local servlet from a jsp, the servlet simply returns a json string:
URL url = new URL("http://myapp.appspot.com/myservlet");
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
String jsonStr = writer.toString();
Can I do this with a relative path so that it works both locally and on the deployed instance?
You could use JSTL with the tag
<c:import>
Alternatively, for your posted code, you could use
String requestURL = request.getRequestURL().toString();
String servletPath = request.getServletPath();
String serverPath = requestURL.substring(0,requestURL.indexOf(servletPath));
URL url = new URL(serverPath + "/myservlet");
You mean like this?
String urlString = "http://localhost/myservlet/";
localhost is an alias for 127.0.0.1, which is always "the local computer".
ServletRequest.getServerPort() will let you know the port where the user connected.
Depending on where this is happening, what you really might want to use is ServletRequest.getRequestDispatcher(), which bypasses the network layer, and stays inside your servlet container.
You can wrap the HttpResponse, and send that through to the RequestDispatcher, then extract the String that was produced with something like this:
http://goo.gl/kRW1b
If the temp string is very large I get java.io.IOException: Error writing to server at getInputStream
String tmp = js.deepSerialize(taskEx);
URL url = new URL("http://"
+ "localhost"
+ ":"
+ "8080"
+ "/Myproject/TestServletUpdated?command=startTask&taskeId=" +taskId + "'&jsonInput={\"result\":"
+ URLEncoder.encode(tmp) + "}");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
Why is that?
This call goes to the servlet mentioned in the URL.
Use HTTP POST method instead of putting all the data in the URL for GET method. There is an upper limit for the length of the URL, so you need to use POST method if you want to send arbitrary length data.
You may want to modify the URL to http://localhost:8080/Myproject/TestServletUpdated, and put the rest
command = "startTask&taskeId=" + taskId + "'&jsonInput={\"result\":" + URLEncoder.encode(tmp) + "}"
in the body of the POST request.
I think you might have a "too long url", the maximum number of characters are 2000 (see this SO post for more info). GET requests are not made to handle such long data input.
You can, if you can change the servlet code also, change it into a POST instead of a GET request (as you have today). The client code would look pretty simular:
public static void main(String[] args) throws IOException {
URL url = new URL("http", "localhost:8080", "/Myproject/TestServletUpdated");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write("command=startTask" +
"&taskeId=" +taskId +
"&jsonInput={\"result\":" + URLEncoder.encode(tmp) + "}");
wr.flush();
.... handle the answer ...
}
I didn't see it first but it seems like you have a single quote character in your request string.
...sk&taskeId=" + taskId + "'&jso.....
^
try removing it, it might help you!
getInputStream() is used to read data. Use getOutputStream()
It could be because the request is being sent as a GET which has a limitation of a very few characters. When the limit exceeds you get an IOException. Convert that to POST and it should work.
For POST
URLConnection conn = url.openConnection().
OutputStream writer = conn.getOutputSteam();
writer.write("yourString".toBytes());
Remove the temp string from the url that you are passing. Move the "command" string to the "yourString".toBytes() section in the code above
I'm trying to open http connection to some given URL in the following form:
http://example.com/xml.aspx?RssType=1&TypeName=中文
I wanted to open an Http connection to it, get its inputStream, and do some parsing on the inputstream (see the code snippet below). But all I get is a MalformedURLException.
Anyone has any idea what's wrong with this URL? is the parameters "?Rss...&..." that's causing the problem or the non-ASCII chars at the end that are problematic?
Code snippet:
String feed = getString(R.string.feed_url);
URL url = null;
HttpURLConnection httpConn = null;
try {
url = new URL(feed);
httpConn = (HttpURLConnection) url.openConnection();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { // exception here!
You need to URL-encode the parameters, in particular that 中文 bit.
Use java.net.URLEncoder.encode("中文", "UTF-8") — to be on the safe side, for every parameter value of the query, not only of TypeName.