Post Json data with HttpURLConnection to REST API server
This is how I send a POST
Let me know if you need any clarification.
public static String executePost(String targetURL, String requestJSON, String apikey) {
HttpURLConnection connection = null;
InputStream is = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
//TODO may be prod or preprod api key
if (apikey.equals(Constants.APIKEY_PREPROD)) {
connection.setRequestProperty("Authorization", Constants.APIKEY_PREPROD);
}
if (apikey.equals(Constants.APIKEY_PROD)){
connection.setRequestProperty("Authorization", Constants.APIKEY_PROD);
}
connection.setRequestProperty("Content-Length", Integer.toString(requestJSON.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
System.out.println(requestJSON);
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(requestJSON);
wr.close();
//Get Response
try {
is = connection.getInputStream();
} catch (IOException ioe) {
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection) connection;
int statusCode = httpConn.getResponseCode();
if (statusCode != 200) {
is = httpConn.getErrorStream();
}
}
}
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();
}
}
}
HttpUrlConnection with post request and parameter as JSON object?
I Found a solution for this by this steps
urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("x-api-key", x_api);
urlConnection.setRequestProperty("Accept", "application/json");
String datajson = "{\"file\": \""+imageString.trim()+"\"}";
Log.e("data","json:"+datajson);
OutputStream os = urlConnection.getOutputStream();
os.write(datajson.getBytes("UTF-8"));
os.close();
How to send JSON data to API using HttpsURLConnection on Android?
Send the request:
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
URL url = new URL ("https://api.url.com/api/token/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try(OutputStream outputStream = conn.getOutputStream()) {
byte[] input = myData.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
To read the response:
StringBuilder sb = new StringBuilder();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
}
System.out.println(sb.toString());
I hope that helps!
How to send Json array as post params in android open URL connection
This sample for your reference
String request = "your Url Here";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Bearer Key");
conn.setRequestProperty("Content-Type", "application/json");
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);
JSONArray jsonArray=new JSONArray();
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
jsonArray.put(jsonParam);
wr.writeBytes(jsonArray.toString());
wr.flush();
wr.close();
For more detail checkout here, here or here
Can't send JSON in a Java HTTP POST request
Thanks to Andreas, it was just missing the line :
connection.setRequestProperty("Content-Type", "application/json");
It works fine now.
Get Json / Resonse body from Curl Post Request in Java
A basic search reveals: https://www.baeldung.com/httpurlconnection-post#8-read-the-response-from-input-stream
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
If the response is in JSON format, use any third-party JSON parsers such as Jackson library, Gson, or org.json to parse the response.
Related Topics
How to Define a List Bean in Spring
Send an Array with an Http Get
Ray Casting with Different Height Size
Why Equals() Method When We Have == Operator
How to Use Java.String.Format in Scala
How to Convert Java String to Date Object
What Makes Reference Comparison (==) Work for Some Strings in Java
How to Set an Image as a Background for Frame in Swing Gui of Java
How to Handle Very Large Numbers in Java Without Using Java.Math.Biginteger
Add Bean Programmatically to Spring Web App Context
Ignore Fields from Java Object Dynamically While Sending as JSON from Spring MVC
How to Split a Java String at Backslash
How to Get Out of While Loop in Java with Scanner Method "Hasnext" as Condition
Comparing Two Java.Util.Dates to See If They Are in the Same Day