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();
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 am writing a Java class to access a third-party public REST API web service, that is secured using a specific APIKey parameter.
I can access the required Json array, using the JsonNode API when I save the json output locally to a file.
E.g.
JsonNode root = mapper.readTree(new File("/home/op/Test/jsondata/loans.json"));
But, if I try to use the live secured web URL with JsonNode
E.g.
JsonNode root = mapper.readTree(url);
I am getting a:
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60))
which suggests that I have a type mismatch. But I am assuming that it is more likely to be a connection issue.
I am handling the connection to the REST service:
private static String surl = "https://api.rest.service.com/xxxx/v1/users/xxxxx/loans?apikey=xxxx"
public static void main(String[] args) {
try {
URL url = new URL(surl);
JsonNode root = mapper.readTree(url);
....
}
I have also tried to use:
URL url = new URL(surl);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
InputStream isr = httpcon.getInputStream();
JsonNode root = mapper.readTree(isr);
with the same result.
When I remove the APIKey I receive a Status 400 Error. So I think I must not be handling the APIKey parameter.
Is there way to handle the call to the secured REST service URL using JsonNode? I would like to continue to use the JsonNode API, as I am extracting just two key:value pairs traversing multiple objects in a large array.
Just try to simply read response into string and log it to see what's actually going on and why you do not receive JSON from server.
URL url = new URL(surl);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
InputStream isr = httpcon.getInputStream();
try (BufferedReader bw = new BufferedReader(new InputStreamReader(isr, "utf-8"))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = bw.readLine()) != null) { // read whole response
sb.append(line);
}
System.out.println(sb); //Output whole response into console or use logger of your choice instead of System.out.println
}
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'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'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