The input I have are a URL and a request payload.
Say,
URL: https://somesresource.com
Payload: {userId: "4566"}
The output I get back is a Json with several key-value pairs.
I tried doing this in Rest Console and the output(Json) looked good. But, when I try to run the following program the output is not the json but the file(html i suppose) from the URL's server. How do I retrieve the Json instead of the file?
#Transactional
#RequestMapping(value = "/xxx", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
String consumer() throws Exception {
String line;
String userId = "12345";
StringBuffer jsonString = new StringBuffer();
URL url = new URL("https://somewebsite/userprofile");
String payload="{\"userId\":\""+sid+"\"}";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
try {
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
System.out.print(connection.getInputStream().toString());
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
}
catch(Exception e) {
}
return jsonString.toString();
}
I think you are missing a converter in your application. I use RestFul Web service with Spring and use MappingJacksonHttpMessageConverter for to & fro conversion of JSON. Please provide more details of your configuration if you are looking for a specific answer.
Related
I'm getting a 'Server returned HTTP response code: 500' error although I have checked what I'm sending (I even tried sending it with an online tool and it worked). The API Key and the JSON are correct. I get this error when trying to read the input stream with 'connection.getInputStream()'. Where could this be comming frome ? Did I forget something ? I am trying to implement this feature from the openrouteservice API : https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/post
public static UPSRoute getRoute(Location start, Location end, String language) {
if (language.equals("fr")) {
JSONObject jsonObject = null;
try {
URL url = new URL("https://api.openrouteservice.org/v2/directions/foot-walking");
String payload = "{\"coordinates\":[[" + start.getCoordinates() + "],[" + end.getCoordinates() + "]],\"language\":\"fr\"}";
System.out.println(payload); //{"coordinates":[[1.463478,43.562038],[1.471717,43.560787]],"language":"fr"}
byte[] postData = payload.getBytes(StandardCharsets.UTF_8);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", API_KEY);
connection.setRequestProperty("Accept", "application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8");
connection.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.write(postData);
}
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); // Error is right here
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
connection.disconnect();
jsonObject = new JSONObject(content.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return new UPSRoute(jsonObject);
} else {
return getRoute(start, end);
}
}
Here is the error :
java.io.IOException: Server returned HTTP response code: 500 for URL: https://api.openrouteservice.org/v2/directions/foot-walking/json
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1913)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:245)
at UPSRouteService.getRoute(UPSRouteService.java:63)
at Main.main(Main.java:5)
Thanks to Andreas, it was just missing the line :
connection.setRequestProperty("Content-Type", "application/json");
It works fine now.
So I have an API project that sends back some JSON data, and depending on which call this data can be formatted in a number of different ways.
Is the correct way to do this to always return data in the same type (like a Collection ) or is to write a method on the non API application using reflection?
Here is my current method for parsing that data, but it won't work if the JSON data doesn't lend itself to being a Collection:
public static Collection<Map> sendPostRequest(String requestURL)
{
StringBuffer jsonString;
try {
URL url = new URL(requestURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<Map>>(){}.getType();
Collection<Map> dataCollection = gson.fromJson(jsonString.toString(), collectionType);
return dataCollection;
}
I hope this questions isn't too open ended, but just need some logistical/best practices help
I have SugarCRM trail account. I can able to get Authenticate and get the AccessToken by the following url.
https://xxxxxxx.trial.sugarcrm.eu/rest/v10/oauth2/token
Method : POST
POST Data : postData: { "grant_type":"password", "client_id":"sugar", "client_secret":"", "username":"admin", "password":"Admin123", "platform":"base" }
Code I used to get the AccessToken
public static String getAccessToken() throws JSONException {
HttpURLConnection connection = null;
JSONObject requestBody = new JSONObject();
requestBody.put("grant_type", "password");
requestBody.put("client_id", CLIENT_ID);
requestBody.put("client_secret", CLIENT_SECRET);
requestBody.put("username", USERNAME);
requestBody.put("password", PASSWORD);
requestBody.put("platform", "base");
try {
URL url = new URL(HOST_URL + AUTH_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.connect();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
out.write(requestBody.toString());
out.close();
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject jObject = new JSONObject(response.toString());
if(!jObject.has("access_token")){
return null;
}
String accessToken = jObject.getString("access_token");
return accessToken;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Now I have retrive Leads from CRM using rest API I can not able to find the appropriate method and Url to do the thing.
I can see the list rest of API's from /help but I cant understand what should be my module name and what I have to :record and how do I pass my access token for authentication.
Can anyone please help me?
The module name is simply the module you which to fetch records from, so in your case you'll want to do a GET request to rest/v10/Leads for a list of Leads. If you want to fetch a specific Lead you replace :record with the id of a Lead - for example: GET rest/v10/Leads/LEAD-ID-HERE
SugarCRM's documentation has a lot of relevant information that might not be included in /help plus working examples.
http://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_7.8/Integration/Web_Services/v10/Endpoints/module_GET/
http://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_7.8/Integration/Web_Services/v10/Examples/PHP/How_to_Fetch_Related_Records/
You need to include your retrieved token into an OAuth-Token header for subsequent requests, and then just use the module name as the endpoint i.e. in your case: "rest/v10/Leads" and call the GET method to retrieve them. Try something akin to this:
String token = getAccessToken();
HttpURLConnection connection = null;
try {
URL url = new URL(HOST_URL + "/rest/v10/Leads");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("OAuth-Token", token);
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.connect();
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject jObject = new JSONObject(response.toString());
System.out.println(jObject);
} catch (Exception e) {
e.printStackTrace();
}
In the case you want to filter it down to specific id's to cut down on the amount of returned data, you can specify it after the module name i.e. "rest/v10/Leads/{Id}"
Updated question
I have modified my client code and restful service code as
updated cliet code is
URL url = new URL("http://localhost:9090/XsdValidation/api/data/xml");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
////
StringBuilder builder = new StringBuilder();
FileReader fileReader = new FileReader("Employee.xml");
BufferedReader reader = new BufferedReader(fileReader);
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
builder .append(line);
}
String xml = builder .toString();
System.out.println("xml file is "+xml);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(xml);
out.close();
reader.close();
updated rest ful service code is
#Path("/data")
public class DataAccess {
#POST
#Path("/xml")
#Consumes(MediaType.APPLICATION_XML)
public String readXml(String file) {
System.out.println("in xml");
return file;
}
}
everything was fine the string i was getting is <?xml version="1.0" encoding="UTF-8"?><empns:employee xmlns:empns="Symplocus/Employee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="Symplocus/Employee Employee.xsd "> <empns:EMP_ID>0101</empns:EMP_ID> <empns:NAME>Rajasekhar</empns:NAME> <empns:SALARY>2000</empns:SALARY> <empns:DATEOFJOINING>2001-01-01</empns:DATEOFJOINING></empns:employee>
i want to convert this whole string to an xml file in order to do validations with xsd .. can any one have an idea to convert string to XML file
////////////////////////////////////////////////////////////////////////////////
////this was the asked previously i got answer for this from GAgarwarl's post///
I was updating the question,now i was able to send xml file to rest ful service,how to read this read this xml on restful service
my client code is
URL url = new URL("http://localhost:9090/XsdValidation/api/data/xml");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
FileReader fileReader = new FileReader("Employee.xml");
StreamSource source = new StreamSource(fileReader);
StreamResult result = new StreamResult(os);
transformer.transform(source, result);
os.flush();
System.out.println(connection.getResponseCode());
//connection.disconnect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
System.out.println("in input stream");
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
System.out.println(connection.getResponseCode());
System.out.println("end of client programme");
and my restful code is
#Path("/data")
public class DataAccess {
#POST
#Path("/xml")
#Consumes(MediaType.APPLICATION_XML)
public String readXml(/here i have to read file /) {
// here i want an idea to read the file sent by client
}
}
////this was old question////
I was completely new to web services,I have to send an XML file in system location like c:/Files/Samle.xml from java client to Restful web service,Previously i have send json object to restful but unable to send xml
my client code to send json is
String tableName="SYMPLOCUS.IMDB1_FINANCE_BUDGE ";
String urlString="http://localhost:9090/DataAccess/api/DataAccess/loadData?tableName="+tableName;
URL url=new URL(urlString);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type",
"application/json");
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
String json = "{\"EMPCODE\":\"125\", \"NAME_TBH\":\"aaaaa\"}";
out.write(json);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
System.out.println("in input stream");
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
System.out.println(httpCon.getResponseCode());
and my restful code is
#Path("/loadData")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String sendReceiveJson(String data,#QueryParam("tableName") String tableName)
{
}
in the same way i wand to send xml file to restful service , can some one have any ideas..
Replace
String json = "{\"EMPCODE\":\"125\", \"NAME_TBH\":\"aaaaa\"}";
With:
StringBuilder builder = new StringBuilder();
FileReader fileReader = new FileReader("fileName");
BufferedReader reader = new BufferedReader(fileReader);
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
builder .append(line);
}
String xml = builder .toString();
Change:
#consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
And also in your client side set:
httpCon.setRequestProperty("content-type","application/xml")
And then send your XML data.
i need toSend POST method with the JSON data ,Make sure i need to send JSON Object serialized into string. Not the JSON string itself.so how can i implement this using JAVA
public static String sendPostRequest(String postURL) throws Exception{
String responseStr=null;
//make POST request
String jsonContent = "{'name': 'newIndia','columns': [{'name': 'Species','type': 'STRING'}],'description': 'Insect Tracking Information.','isExportable': true}";
//String data = "{\"document\" : {\"_id\": \"" + id+ "\", \"context\":" + context +"}}";
URL url = new URL(postURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(jsonContent.getBytes().length));
connection.setUseCaches(false);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(jsonContent);
writer.close();
responseStr="Response code: "+connection.getResponseCode()+" and mesg:"+connection.getResponseMessage();
System.out.println(connection.getResponseMessage());
InputStream response;
// Check for error , if none store response
if(connection.getResponseCode() == 200){
response = connection.getInputStream();
}else{
response = connection.getErrorStream();
}
InputStreamReader isr = new InputStreamReader(response);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(isr);
String read = br.readLine();
while(read != null){
sb.append(read);
read = br.readLine();
}
// Print the String
System.out.println(sb.toString());
connection.disconnect();
return responseStr;
}
For more you can see this example.
I would recommend using Jersey REST framework which works great with GAE. Here is a demo.
Using gson, you can POST JSON data to a web-service very easily.
For example:
public class MyData { //var myJsonData = {
private boolean fans = true; // fans:true,
private boolean funds = true; // funds:true
//private String chart = "day"; // }
}
Now send the POJO to a real web-service:
public class Main {
public static void main(String... args) throws Exception {
URL theUrl = new URL("https://robertsspaceindustries.com/api/stats/getCrowdfundStats");
Gson gson = new Gson();
JsonParser jp = new JsonParser();
MyData thedata = new MyData();
HttpsURLConnection urlConnection = (HttpsURLConnection) theUrl.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true); //allow parameters to be sent/appended
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes(gson.toJson(thedata)); //convert the POJO to JSON, then to binary.
wr.flush();
wr.close();
urlConnection.connect(); //start request transmission
JsonElement retJson = jp.parse(new InputStreamReader((InputStream) urlConnection.getContent())); //convert the input stream to a json element
System.out.println(retJson.getAsJsonObject());
urlConnection.disconnect(); //end request transmission
}
}
Replies with:
{"success":1,"{"fans":910125,"funds":8410319141},"code":"OK","msg":"OK"}
(Note, the equivalent cURL command at time of writing was) ->
curl 'https://robertsspaceindustries.com/api/stats/getCrowdfundStats' --data-binary '{"fans":true,"funds":true}'