How to send HTTP request in java?
You can use java.net.HttpUrlConnection.
Example (from here), with improvements. Included in case of link rot:
public static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
How do I send a java object in a HTTP Request?
Firstly you have to make your Place class serializable, by
implementing java.io.Serializable
Then the Place object needs to be converted to a json object, which can be done easily by using Jackson or GSON libraries.
Example using Gson:
Gson gson = new Gson();
String json = gson.toJson(placeObject);
Later while receiving the response you can deserialize it back to Place object using the same library.
Place placeObject = new Gson().fromJson(json, Place.class);
sending HTTP POST requests in Java
So I did some research and found this!
package com.*********.xyz;
import java.io.IOException;
import java.util.Scanner;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
String body = "this is the message you are going to post!";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://192.168.1.46:4046/authenticate"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response);
//Should print 200 after sending the response if the server is active
}
}
This code works without any third-party libraries.
Java doesn't send HTTP POST Request
I tested this and it's working:
//Sender.java
String url = "http://localhost:8082/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write("Just Some Text".getBytes("UTF-8"));
os.flush();
int httpResult = con.getResponseCode();
con.disconnect();
As you can see, connect is not necessary. The key line is
int httpResult = con.getResponseCode();
What is the best way to make an HTTP request from a Java program?
https://square.github.io/okhttp/ is a good library for http interaction. Then you can use Jackson/Gson to parse the response to a typed object if you want
Usage
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
Maven:
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.4.0</version>
</dependency>
or Gradle:
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
If you want to kill an ant with a Patton Tank, you have all sort of other options like spring, netflix OSS - feign client + ribbon etc
That being said, first, I would try out what Kayaman posted, https://www.baeldung.com/java-9-http-client as its one less dependency.
How to send a correct HTTP PUT request in Java
You are using the wrong URL for the PUT request.
A GET request to http://192.168.0.53/api/.../lights/1
will return the current state
But to modify you need a PUT request to http://192.168.0.53/api/.../lights/1/state
Related Topics
Remove HTML Tags from a String
Why Doesn't Recyclerview Have Onitemclicklistener()
How to Declare a Variable in Gradle Usable in Java
Virtual Memory Usage from Java Under Linux, Too Much Memory Used
Should I Avoid the Use of Set(Preferred|Maximum|Minimum)Size Methods in Java Swing
What Is the Reason Behind "Non-Static Method Cannot Be Referenced from a Static Context"
When Do You Use Java'S @Override Annotation and Why
How to Concatenate Two Arrays in Java
Does a Finally Block Always Get Executed in Java
How to Properly Stop the Thread in Java
How to Send Http Request in Java
How to Write Files to External Public Storage in Android So That They Are Visible from Windows
How to Set Httpresponse Timeout For Android in Java
Running Jmap Getting Unable to Open Socket File
What's the Simplest Way to Print a Java Array
Connect to Kafka Running in Docker
How to Invoke a Java Method When Given the Method Name as a String