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);
Related
I'm trying to send a Json format in body of POST request in java.
I tried a lot of codes from the internet and StackOverflow, but nothing is working.
I keep getting java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8080/engine-rest/message.
After trying a lot on Postman i noticed it only accepts Json format body, i tried using json libraries like Gson, yet still nothing worked.
Any ideas on how to fix my code? Again I did try to copy a lot of codes from the internet so please don't send me a similar title stackoverflow thread and call the question repetitive.
Thank you in advance.
public class PostRequest {
FileWriter myWriter;
URL url;
public void sendPost(String Url) throws IOException {
String name = "{\"messageName\": \"URLFound\", \"businessKey\": \"3\"}";
try {
myWriter = new FileWriter("C:\\Users\\test\\Desktop\\camunda test save\\Post.txt");
url = new URL ("http://localhost:8080/engine-rest" + Url);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/json");
OutputStream os = http.getOutputStream();
byte[] input = name.getBytes("utf-8");
os.write(input, 0, input.length);
BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuffer response = new StringBuffer();
while ((in.ready())) {
response.append(in.readLine());
}
in.close();
//Writing result on .txt
myWriter.append(response.toString() + "\n" +url);
}
catch(Exception e){
myWriter.append(e.toString());
}
myWriter.close();
}
}
How about using this client project?
https://github.com/camunda-community-hub/camunda-rest-client-spring-boot/
For example:
https://github.com/camunda-community-hub/camunda-rest-client-spring-boot/blob/dce6bd777e3350dd30286311c5351aa9460a34f4/examples/example/src/main/java/org/camunda/bpm/extension/rest/example/standalone/client/ProcessClient.java#L98
Java cant create an object from your json. Check if all fields are sent in the request body of the java class that is expected on the backend side.
I'm trying to access all the jira issues using the jira-rest-api url in the following way:
URL url;
url = new URL("http://ficcjira.xyz.com/rest/api/2/search?jql=project=ABC&fields=timespent");
URLConnection conn = url.openConnection();
String auth = "username" + ":" + "password";
byte[] authBytes = auth.getBytes(StandardCharsets.UTF_8);
String encodedAuth = Base64.getEncoder().encodeToString(authBytes);
conn.setRequestProperty("Authorization", "Basic " + encodedAuth);
try (InputStream responseStream = conn.getInputStream()) {
//JsonElement element = new JsonParser(stream).parse(responseStream);
// To read response as a string:
MimeType contentType = new MimeType(conn.getContentType());
String charset = contentType.getParameter("charset");
#SuppressWarnings("resource")
String response =
new Scanner(responseStream, charset).useDelimiter("\\Z").next();
I get a response from the url as a JSON response. What do I do next to display the response to the console?
UPDATE:
Geting Null pointer exception when trying to do System.out.printn(response);
System.out.println(response) : to print to console
And also you can avoid boilerplate code by using the libraries. For example, you can replace all your code with below single line.
String response = IOUtils.toString(new URL("http://ficcjira.xyz.com/rest/api/2/search?jql=project=ABC&fields=timespent"));
IOUtils is part of apache commons.
You can simply use a System.out.print(); of the string response you streammed
I have a problem with Java HTTP. I am trying to make an app, which will send a certain request to the server and then get needed data. I have found how to send GET to the server, but I fully stuck then. I've found bunch of ways to parse search results in Google, but no info concerning other web resourses. So, for example, I'd like to make a custom search for transport tickets from some web-site - what should I do? If it somehow helpful - here is the code Im using for GET.
public static void main(String[] args) throws UnsupportedEncodingException, MalformedURLException, IOException {
String url = "https://www.example.com/tickets/search";
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String param1 = "value1";
String param2 = "value2";
String query = String.format("param1=%s¶m2=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
try (Scanner scanner = new Scanner(response)) {
String responseBody = scanner.useDelimiter("\\A").next();
System.out.println(responseBody);
}
}
For this kind of need, I like using DavidWebb a Lightweight Java HTTP-Client for calling JSON REST-Services. Here is how you code would look like using this library (assuming that you expect a result in JSON):
Webb webb = Webb.create();
JSONObject result = webb
.post("https://www.example.com/tickets/search")
.param("param1", "value1")
.param("param2", "value2")
.asJsonObject()
.getBody();
I have an application (Java) that needs to send json to a php web service.
This is my method to send User in JSON :
public void login(User user) throws IOException {
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
String url = "http://localhost/testserveur/index.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("json", json);
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.flush();
}
int responseCode = con.getResponseCode();
System.out.println(responseCode);
}
And my php code :
$string=$_POST['json'];
I tried to insert in my database but $_POST['json'] does not exist.
I didn't see you to posting anything. Add this to your code:
String param = "json=" + URLEncoder.encode(json, "UTF-8");
wr.write(param.getBytes());
This is not right:
con.setRequestProperty("json", json);
setRequestProperty is not used to set the HTTP payload. It is used to set the HTTP headers. For example, you should set the content type accordingly anyway. Like this:
con.setContentType("application/json");
The actual data that you are going to post goes into the HTTP body. You just write it to the end of the stream (before flush):
Here it depends on your implementation on the web server if the data needs to be escaped. If you read the body of the post and interpret it as JSON straight away, it does not need to be escaped:
wr.write(json);
If you transmit one or more JSON strings through parameters (which it looks like, since you are parsing it on the server like $_POST['json']), then you need to url-escape the string:
wr.write("json=" + URLEncoder.encode(json, "UTF-8"));
Im not very familiar with php. You might need to url-decode the string on the server before processing the received json-string any further.
Thx for your help.
This works :
public void login(User user) throws IOException {
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
String url = "http://localhost/testserveur/index.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("json", json);
OutputStream os = con.getOutputStream();
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
//wr.write(new String("json=" + json).getBytes());
String param = "json=" + URLEncoder.encode(json, "UTF-8");
wr.write(param.getBytes());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println(responseCode);
}
PHP :
$string=$_POST['json'];
I'm trying to setup a basic call to a Spring service using the URL package so that I can do it through a POST rather than get.
Client code (the code calling the spring service):
String data = URLEncoder.encode("testStringFromGWT", "UTF-8") + "=" + URLEncoder.encode(message, "UTF-8");
URL url = new URL("http://localhost:8080/spring-hibernate-mysql/test/test1");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
The Spring service:
#RequestMapping(value = "/test1", method = RequestMethod.POST)
public String loggedInUniversal_logout(
Model model,
HttpServletRequest request,
#RequestParam(value = "inputString", required = true) String inputString)
throws InterruptedException {
HttpSession session = request.getSession();
System.out.println("Request made from Client..." + inputString);
model.addAttribute("token", "It works");
return "token";
}
When I try this I get:
java.io.FileNotFoundException: http://localhost:8080/spring-hibernate-mysql/test/test1
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1401)
I'm not quite sure what I am doing wrong, I am able to confirm that the call is being passed through properly to Spring as I can see the line being printed "Request made from Client..." + inputString but then I get the FileNotFoundException on the client. I pieced this together from looking at tutorials so I guess I am missing something here, would appreciate any advice.
Close the output stream before trying to read from the input stream in your example above.
As an alternative, use a http client library like HTTPClient or Resty.
With Resty, your client code would look like this:
Resty r = new Resty();
String result = r.text(url).toString();
for a GET
and for a POST using a simple form:
r.text(url,form(yourformdata)).toString();
Disclaimer: I'm the author of Resty