How to pass JSON body in HTTP Put in JAVA - java

Can someone explain me how to pass JSON parameter in request body.
I am using HttpURLConnection to create the connection, as below:
URL uri = null;
HttpURLConnection con = null;
try{
uri = new URL(url); //URL is hardcoded as of now
con = (HttpURLConnection) uri.openConnection();
con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
con.setDoOutput(true);
con.setDoInput(true);
con.setConnectTimeout(60000); //60 secs
con.setReadTimeout(60000); //60 secs
con.setRequestProperty("Accept-Encoding", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("cache-control", "no-cache");
con.setRequestProperty("Postman-Token", "448b7c42-61f1-4373-8a7d-80a0a4610b99");
JSONObject reqBody = new JSONObject();
reqBody.put("state", "4");
System.out.println(reqBody);
StringEntity params = new StringEntity(reqBody.toString());
if( reqBody != null){
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
How can I put set the req body here?

For specifying the body of your request:
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(reqBody.toString());
wr.flush()

Related

HTTP error 400 Bad Request when POSTing JSON data over HttpURLConnection

I am trying to connect to sharepoint to get the access token.I am using below code to call the api but getting 400 bad request.It's working with postman.
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// conn.setRequestProperty("Accept", "application/json;");
// conn.setRequestProperty("x-csrf-token", "fetch");
// conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
// conn.setRequestProperty("Accept-Charset", "UTF-8");
// conn.setRequestProperty("User-Agent", "Java client");
JSONObject obj2 = new JSONObject();
obj2.put("grant_type", mygranttype);
obj2.put("client_id", clientid);
obj2.put("client_secret", secret);
obj2.put("resource", resource);
// System.out.println(conn.getHeaderFields());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
out.write(obj2.toString());
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
I tried below options:
// conn.setRequestProperty("x-csrf-token", "fetch");
// conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
// conn.setRequestProperty("Accept-Charset", "UTF-8");
// conn.setRequestProperty("User-Agent", "Java client");

API require GET method but need to send parameters

i need to send some parameters to the API which accept as it seems only GET method...if i join parameters Im unable to send it through GET method and with POST method I'm getting 404 - not found for the call...
already tried different methods of joining parameters to the call but no luck
// Documentation - https://coinmarketcap.com/api/documentation/v1/#section/Quick-Start-Guide
String apiKey = "707e6117-e462-4de3-9748-98ab6a467f0c"; // my temp key feel free to use it
HttpURLConnection urlConnection = null;
URL url = new URL("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("X-CMC_PRO_API_KEY", apiKey);
Map<String, String> parameters = new HashMap<>();
parameters.put("start", "1");
parameters.put("limit", "5000");
parameters.put("convert", "USD");
urlConnection.setDoOutput(true);
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
urlConnection.connect();
int status = urlConnection.getResponseCode();
String message = urlConnection.getResponseMessage();
I would like to have results from API
The documentation only mention GET method. Add the parameters as standard HTTP GET parameters:
String apiKey = "707e6117-e462-4de3-9748-98ab6a467f0c";
final String request = "start=1&limit=500&convert=USD";
HttpURLConnection urlConnection = null;
URL url = new URL("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?" + request);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("X-CMC_PRO_API_KEY", apiKey);
try (BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())))
{
String line = br.readLine();
while (line != null)
{
System.out.println(line);
line = br.readLine();
}
}
String apiKey = "707e6117-e462-4de3-9748-98ab6a467f0c"; // my temp key feel free to use it
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
RestTemplate restTemplate = new RestTemplate();
String url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("start", "1");
map.add("limit", "5000");
map.add("convert", "USD");
map.add("ReadTimeout", "10000");
map.add("ConnectTimeout", "15000");
map.add("X-CMC_PRO_API_KEY", apiKey);
System.out.println(map);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
System.out.println(response.getBody());
}

My RESTful API with Node/Express wrong codification of caracters

I have an applicaction that makes a post request inserting a user like this:
email=Ali#gmail.com&name=Alí
But then hits the server with a wired caracter
...
body: {
email: Ali#gmail.com,
name: Al?
}
And is like this how is save in the database.
My code in the server is simple
router.post('user', (req, res) => {
const newUser = new User({
email: req.body.email,
name: req.body.name
});
newUser.save().then((usr) => {
const resp = { user: usr.fields(), code: 200 };
return res.status(200).send(resp);
}).catch(err => {
console.log(err);
});
});
The client is using HTTPConnection in Java:
StringBuffer response = new StringBuffer();
HttpURLConnection con = null;
URL obj = new URL(url);
obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(3306);
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("charset", "utf-8");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
if (params != null) {
wr.writeBytes(params);
}
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
I think you should escape the "í" character in your url request (client side).
Something like
email=Ali#gmail.com&name=Al%ED%20%0A

JAVA Send Post Request which contains XML String

Problem Description
I'm trying to write a code which is sending POST request to the server. As server yet doesn't exist I can't test this part of code. With the request I must send XML as a String which look likes the string below:
String XMLSRequest = "<?xml version="1.0" encoding="UTF-8" standalone="no"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header><AuthenticationHeader><Username>Victor</Username><Password>Apoyan</Password></AuthenticationHeader></soapenv:Body></soapenv:Envelope>"
Solution
String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = String.format("request=%s", XMLSRequest);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Question
Is this right way to send String (XML like string) as POST request to the server?
To POST a SOAP request, you would want to write the xml to the body of the request. You do not want to write it as a parameter of the request.
String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
urlConnection con = (HttpsURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
// Send post request
con.setDoOutput(true);
OutputStream os = con.getOutputStream(); //get output Stream from con
os.write( XMLSRequest.getBytes("utf-8") );
os.close();
Specially this code works well for sending XML string in SOAP calling
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public static String sendXmlString(String xmlString){
String xmlResponceString = "";
try {
// Replace here with your target URL
URL url = new URL("http://www.dneonline.com/calculator.asmx");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set timeout as per needs
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
// Set DoOutput to true if you want to use URLConnection for output.
// Default is false
connection.setDoOutput(true);
connection.setUseCaches(true);
connection.setRequestMethod("POST");
// Set Headers
connection.setRequestProperty("Accept", "*/xml");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("User-Agent", "");
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Write XML
OutputStream outputStream = connection.getOutputStream();
byte[] b = xmlString.getBytes("UTF-8");
outputStream.write(b);
outputStream.flush();
outputStream.close();
// Read XML
InputStream inputStream = connection.getInputStream();
byte[] res = new byte[2048];
int i = 0;
StringBuilder response = new StringBuilder();
while ((i = inputStream.read(res)) != -1) {
response.append(new String(res, 0, i));
}
inputStream.close();
xmlResponceString = new String(response.toString());
} catch (IOException e) {
e.printStackTrace();
}
return xmlResponceString;
}

Send request to Google Elevation API in Java

I'm try to send Post request to Google elevation API and expecting response
private final String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/json";
private final String USER_AGENT = "Mozilla/5.0";
String urlParameters = "locations=6.9366681,79.9393521&sensor=true&key=<API KEY>";
URL obj = new URL(ELEVATION_API_URL);
java.net.HttpURLConnection con = (java.net.HttpURLConnection)obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Language", "en-US");
String urlParameters = request;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
I'm sending request in this manner but I'm getting response code as 400.This is working when request sent from browser. What is wrong with this code.
To Allow me to get XML back I made the following changes to your project
StringBuilder response = new StringBuilder(); // placed on the top of your Class
**wr.writeBytes(urlParameters.toString());** // as you have it in your code
System.out.println("ResponseMessage : " + connection.getResponseMessage());
System.out.println("RequestMethod : " + connection.getRequestMethod());
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
wr.flush();
wr.close();
// I changed the URL to :
private final String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/xml";
//**I get XML in the response**
return response.toString();
I think there is a problem with the url parameters.
Firstly because sending an empty elevation api request does return a code 400 (Invalid request. Missing the 'path' or 'locations' parameter.).
Secondly because this works (returning 200) :
public void test() throws Exception {
String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/json";
String USER_AGENT = "Mozilla/5.0";
String urlParameters = "locations=6.9366681,79.9393521&sensor=true";
URL obj = new URL(ELEVATION_API_URL + "?" + urlParameters);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Language", "en-US");
//String urlParameters = request;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
}

Categories