get JSON response while performing POST request with HttpURLConnection - java

I am using the following code to perform POST requests on a REST API. It is all working fine. What I am being unable to do is after POST is successful the API returns response JSON in body with headers, this JSON has information which I require. I am unable to get the JSON response.
I need this response as this response includes the ID generated by DB. I can see the response while using REST Client plugin of firefox. Need to do implement the same in Java.
String json = "{\"name\": \"Test by JSON 1\",\"description\": \"Test by JSON 1\",\"fields\": {\"field\": []},\"typeDefinitionId\": \"23\",\"primaryParentId\": \"26982\"}";
String url = "http://serv23/api/contents";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//Setting the Request Method header as POST
con.setRequestMethod("POST");
//Prepairing credentials
String cred= "user123:p#ssw0rd";
byte[] encoded = Base64.encodeBase64(cred.getBytes());
String credentials = new String(encoded);
//Setting the Authorization Header as 'Basic' with the given credentials
con.setRequestProperty ("Authorization", "Basic " + credentials);
//Setting the Content Type Header as application/json
con.setRequestProperty("Content-Type", "application/json");
//Overriding the HTTP method as as mentioned in documentation
con.setRequestProperty("X-HTTP-Method-Override", "POST");
con.setDoOutput(true);
JSONObject jsonObject = (JSONObject)new JSONParser().parse(json);
OutputStream os = con.getOutputStream();
os.write(jsonObject.toJSONString().getBytes());
os.flush();
WriteLine( con.getResponseMessage() );
int responseCode = con.getResponseCode();

Get the input stream and read it.
String json_response = "";
InputStreamReader in = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(in);
String text = "";
while ((text = br.readLine()) != null) {
json_response += text;
}

Related

400 Error Paypal Token API with Java (HttpURLConnection)

I am trying to integrate Paypal using Jave(using HttpURLConnection)
API for getting token in Paypal
JDK version-1.8
Requirements:
Basic Auth Authentication -username and password.
Copied the value from Postman and added as Authentication in Header.
Body - grant_type=client_credentials as application/x-www-form-urlencoded
Adding my code:
String url = "https://api.sandbox.paypal.com/v1/oauth2/token";
HttpURLConnection con = null;
BufferedReader in = null;
String response = "";
String urlParameters="";
URL obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("POST");
urlParameters = "grant_type=client_credentials";
//add request header
con.setRequestProperty("authorization", "Basic Value");
con.setRequestProperty("content-type","application/x-www-form-urlencoded");
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(urlParameters);
// For POST only - START
OutputStream os = con.getOutputStream();
os.flush();
os.close();
I am getting a 400 error for all API requests.
Please help.
Is this the correct way to add the body part.

I need to send a POST request to an api using an XML request structure in java

String urly = "myurl";
URL url = new URL(myurl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","application/xml");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(xml);
wr.flush();
i am not sure whether this sends the request using xml request structure which is stored in String "xml". I dont know any other way to send request using XML.
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader iny = new BufferedReader(new InputStreamReader(con.getInputStream()));
String output;
StringBuffer res = new StringBuffer();
while ((output = iny.readLine()) != null) {
res.append(output);
}
iny.close();
wr.close();
//printing result from response
System.out.println(res.toString());
The response i am getting shows Invalid Request.
The generated XML was wrong, it needed to be checked.

HttpURLConnection returning 400 status on post call without payload

Actually there are two POST URLs. First POST url is login as follows and even it contains body as json as follows.
String loginUrl = "http://00.00.00.00:0000/url/vs1/login";
json = `{"email": "qqqq#mail.com", "password": "/JGgdwd6vhsvJJFGDF7ttd="}`
Second POST url without payload as follows.
String SiteLoginUrl = "http://00.00.00.00:0000/url/vs1/site/1/login";
So first, above first url need to login then only i can login to second url.
Hence first URL is logging in successfully but after getting response i need to login for second URL which doesn't consists of payload or json. So after calling second URL with POST is returning 400 error. For second URL i have written code below.
// java HttpURLConnection for POST without json or payload data
String SiteLoginUrl = "http://00.00.00.00:0000/url/vs1/site/1/login";
HttpURLConnection conn = (HttpURLConnection) new URL(SiteLoginUrl).openConnection();
conn.setDoOutput(true);
conn.setUseCaches(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("ContentType","application/json;charset=UTF-8");
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
JSONObject obj = new JSONObject();
wr.writeBytes(obj.toString()); //String Empty Object
wr.flush();
wr.close();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return 1;
} else {
return 0;
}
In POSTMAN i checked it is working fine (returning successful login response) with text {}(String Empty Object) payload.

OData Bad Request 400 with Java Client

I have an issue regarding OData querying with an Java Client.
If I use Postman, everything works as expected and I'm receiving a response from the web service with the metadata. But in my Java Client, which runs not on the SCP / HCP I'm receiving "400-Bad Request". I used the original Olingo libary.
I only used the $metadata Parameter, so there is no filter value or something else.
public void sendGet(String user, String password, String url) throws IOException, URISyntaxException {
// String userPassword = user + ":" + password;
// String encoding = Base64.encodeBase64String(userPassword.getBytes("UTF-8"));
URL obj = new URL(url);
URL urlToEncode = new URL(url);
URI uri = new URI(urlToEncode.getProtocol(), urlToEncode.getUserInfo(), urlToEncode.getHost(), urlToEncode.getPort(), urlToEncode.getPath(), urlToEncode.getQuery(), urlToEncode.getRef());
// open Connection
HttpURLConnection con = (HttpURLConnection) uri.toURL().openConnection();
// Basis Authentifizierung
con.setRequestProperty("Authorization", "Basic " + user);
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("Content-Type", "application/xml");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
response.append("\n");
}
in.close();
// print result
System.out.println(response.toString());
// Schließt eine Vorhandene Verbindung
con.disconnect();
in User is already the encoded value. by manipulating this one, i'm receiving an authorization error, so already tested.
May somebody can help me in that case :)
Thanks in advance.
Tim
So I solved it by myself.
i added the statement con.setRequestProperty("Accept", "application/xml"); and it works fo me.
Maybe it could help somebody else.

HttpURLConnection header

I am new to user java to connect to server. I have succeed in forming a json which has some key and value to form the body to call the api service and get successful response (with the following code).
My questions are:
Some of my web service just request header info, for example, I just need to
put the ApiKey(key name) and key value in the header and send to server, no other info is needed in body, how can I do this?
Some of my web service require both header info and body info, how can I construct the json and send to server?
try {
String input = jsonString;
URL url = new URL("https://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
System.out.println("errorcode" + conn.getResponseCode());
if (conn.getResponseCode() != 200) {
JOptionPane.showMessageDialog(new JFrame(), "Please input a correct username or password");
return;
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String jsonText = read(br);
System.out.println("jsonText: " + jsonText);

Categories

Resources