I have to write the most basic POST client in Java.
It sends a few parameters to a Certificate server.
The parameters are supposed to be JSON encoded
I have the attached code, how do I make the params JSON encoded?
String url = "http://x.x.x.x/CertService/revoke.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "serialnumber=C02G8416DRJM&authtoken=abc&caauthority=def&reason=ghi";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
Can you just set your content type as application/json and send the json string?
con.setRequestProperty("Content-Type", "application/json");
The text you're POSTing in your example looks like it's application/x-www-form-urlencoded. To get application/json encoding, prepare the parameters as a map, then use any of several JSON encoding libraries (e.g., Jackson) to convert it to JSON.
Map<String,String> params = new HashMap<>();
params.put("serialnumber", "C02G8416DRJM");
params.put("authtoken", "abc");
...
ObjectMapper mapper = new ObjectMapper();
OutputStream os = con.getOutputStream();
mapper.writeValue(os, params);
os.flush();
os.close();
...
Related
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.
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.
i want get json from this url
but get error like this :
java.io.IOException: Server returned HTTP response code: 403 for URL: http://test.dotconnect.io/data_api/reports/1bf4bc70b31d4d92b50a6d965c52fcec
this is my complete code :
InputStream is = null;
JsonReader rdr = null;
OutputStreamWriter out = null;
String path = "http://test.dotconnect.io/data_api/reports/";
int timeout = 6000000;
String key ="Authorization : 402c669e45534f868f5d2dd53c8e345f,a80797e0df9c4696b5494635dae02461";
URL url = new URL(path+request.getParameter("reportTaskToken"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setDoInput(true); // Triggers GET
connection.setDoOutput(true);// Triggers POST
connection.setRequestProperty("Authorization", key);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
System.setProperty("http.agent", "Chrome");
System.setProperty("http.proxyHost", "proxy.smmf.co.id");
System.setProperty("http.proxyPort", "8080");
out = new OutputStreamWriter(connection.getOutputStream());
out.flush();
out.close();
is = connection.getInputStream();
rdr = Json.createReader(is);
but when i try in postman it's work,
I've read on stackoverflow but still have errors like that
Someone could help me?
Thank You, a greeting,
Try modifying key variable from
String key ="Authorization : 402c669e45534f868f5d2dd53c8e345f,a80797e0df9c4696b5494635dae02461";
// to something like below
String key ="402c669e45534f868f5d2dd53c8e345f,a80797e0df9c4696b5494635dae02461";
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;
}
I have written a Java Code to test the Watson Question and Answers API. However, I'm getting response code 500, when I run it. I have checked the api url and my login credentials. The problem seems to be somewhere else. Any hints or debugging suggestions would be of great help.
String url = "https://watson-wdc01.ihost.com/instance/526/deepqa/v1/question";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
String userCredentials = "username:password";
String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestProperty("X-SyncTimeout", "30");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestMethod("POST");
String query = "{\"question\": {\"questionText\": \"" + "What are the common respiratory diseases?" + "\"}}";
System.out.println(query);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(query);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
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);
}
in.close();
//print result
System.out.println(response.toString());
When i open the same url with the browser I get this:
Watson Error!!
Error Encountered!!
Unable to communicate with Watson.
Whats wrong? Could it be something with the configuration? Or is the server down?
Any hints or debugging suggestions would be of great help.
Attempt the same request using your web browser ... or the curl utility.
Capture and output the contents of the error stream.
I don't think that this is the cause of your problems, but it is wrong anyway:
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(query);
wr.flush();
You are writing to an API that expects text (JSON). You should therefore use a Writer, not a data (binary) output stream:
Writer wr = new OutputStreamWriter(con.getOutputStream(), "LATIN-1");
wr.write(query);
wr.flush();