I'm trying to invoke following code.
// object
LoginVM loginVM = new LoginVM();
loginVM.setUserName("admin");
loginVM.setUserPassword("s#1234");
loginVM.setClientIpAddress("::1");
loginVM.setIsPinActive(false);
loginVM.setLoginWithPIN(false);
//connection
URL url = new URL("http://192.168.202.118/UMService/UserLogin/Login");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty( "Content-Type", "application/json");
conn.setDoOutput(true); //this is to enable writing
conn.setDoInput(true); //this is to enable reading
ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writeValueAsString(loginVM);
System.out.println(jsonInString);
ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
out.writeObject(jsonInString);
out.flush();
The service is successfully . But LoginVM 's values got null.Could you please point what is the error I have made?
Should work with something like:
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(jSonResponse);
You need to check the object in which you are assigning the response.
Also, check among JsonObject or array accordingly.
Related
Good day everyone please I am supposed to send back a JSON object as a response from my service using RestTemplate but I am confused about where to add the JSON data with restTemplate.exchange() method.
Please see the code below.
Thank you in advance.
JSONObject json= new JSONObject();
json.put("responseCode", 200);
json.put("responseMessage", "Transaction Successfully proceed");
json.put("responseData", transactionDetail.toJson());
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(headers);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
MappingJackson2HttpMessageConverter jsonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
jsonHttpMessageConverter.getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
restTemplate.getMessageConverters().add(jsonHttpMessageConverter);
ResponseEntity<String> resultFromVGIL = restTemplate.exchange(bitbackCallBackUrl, HttpMethod.POST, entity, String.class);
I was supposed to add the json object in the HttpEntity
HttpEntity<Object> entity = new HttpEntity<>(json.toString(), headers);
In Java, I am adding some properties to a JSON object, and sending those values to an HTTPS URL (REST API). The server throws some error like "invalid utf-8 start byte 0xb0". Below is my code:
final String urlString = "https://connect.pointclickcare.com/api/public/preview1/orgs/"+vitalStat.get("customer")+"/observations";
String authorization = "Bearer "+vitalStat.get("accessToken");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", vitalStat.get("type"));
jsonObject.addProperty("patientId", patientInfo.getPatientId());
jsonObject.addProperty("deviceId", vitalStat.get("deviceId"));
jsonObject.addProperty("deviceName", vitalStat.get("deviceName"));
jsonObject.addProperty("recordedDate", vitalStat.get("recordedDate"));
jsonObject.addProperty("value", vitalStat.get("value"));
jsonObject.addProperty("method", vitalStat.get("method"));
if(vitalStat.get("type").equals("temperature"))
{
jsonObject.addProperty("unit", "°F");
}
else{
jsonObject.addProperty("unit", vitalStat.get("unit"));
}
if(vitalStat.get("type").equals("bloodPressure"))
{
String[] split = vitalStat.get("value").split("/");
jsonObject.addProperty("systolicValue", split[0]);
jsonObject.addProperty("diastolicValue", split[1]);
jsonObject.remove("value");
}
HttpURLConnection connection = null;
try {
final URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.POST);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",MediaType.APPLICATION_JSON);
connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON);
connection.setRequestProperty("Authorization", authorization);
final OutputStream outputStream = connection.getOutputStream();
final DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeBytes(jsonObject.toString());
dataOutputStream.close();
System.out.println(connection.getResponseMessage());
You don't want to use DataOutputStream. It has its own data encoding and is certainly not compatible with JSON. Instead, you have to serialize your JSON data such that a string representation of JSON (in UTF-8) is generated.
I assume that you are using JsonObject from org.json. In that case, the code should looks something like this:
final OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
jsonObject.write(writer);
I am posting JSON object using spring rest template. It works fine for less data, but posting more data throws a Request URI too long error.
final String url = getServiceUrl() + "/rs/doc?param1=test";
RestTemplate restTemp=getRestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
//set your entity to send
HttpEntity<MyBean> request = new HttpEntity<MyBean>(myBean,headers);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new MappingJacksonHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
restTemp.getMessageConverters().addAll(messageConverters);
// send it!
responseEntity = restTemp.exchange(url, HttpMethod.POST, request, String.class);
The request body should accept unlimited data in POST method. But that doesn't seem to work here. Can someone please guide.
Below is working fine for me. I have added security details in the header and the post parameters that I need to sent.
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.set(ApplicationConstants.API_KEY, ApplicationConstants.TEST_API_KEY_VALUE);
headers.set(ApplicationConstants.AUTH_TOKEN, ApplicationConstants.TEST_API_TOKEN_VALUE);
MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
postParameters.add("purpose", cust.getPaymentPurpose());
postParameters.add("buyer_name", cust.getCustomerName());
postParameters.add("email", cust.getCustomerEmailId());
postParameters.add("phone", cust.getCustomerMobNum());
postParameters.add("send_email", "False");
postParameters.add("send_sms", "False");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(postParameters, headers);
ResponseEntity<String> result = restTemplate.exchange("YOUR URL", HttpMethod.POST, requestEntity, String.class);
OnlinePaymentModel paymentModel = gson.fromJson(result.getBody(), OnlinePaymentModel.class);
I am having problems indexing in elasticsearch. I have a function which creates an index and another one that creates a type mapping for a json I will be indexing. Both of these work fine but when I try calling the function to index something, it gives me a WebException saying that the remote server returned an error: (503) Server Unavailable. Any help will be greatly appreciated! Thanks!
This is my code:
public static void Main(string[] args)
{
string endpoint = "http://localhost:9200";
string index = "logs";
string type = "activity-log";
createIndex(endpoint, index);
createMapping(endpoint, index, type);
indexEvent(endpoint, index, type);
}
public static void createIndex(string endpoint, string index)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/", endpoint, index));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use POST method when creating an index
string json = "{\"settings\":{\"number_of_shards\":3,\"number_of_replicas\":2}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
public static void createMapping(string endpoint, string index, string type)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/{2}/_mapping", endpoint, index, type));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use POST method when creating an index
string json = "{\"activitylogevent\":{\"properties\":{\"id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"parentId\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"event\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
public static void indexEvent(string endpoint, string index, string type)
{
//build the request URL
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/{2}/", endpoint, index, type);
request.ContentType = "application/json"; //set content type of json
request.Method = "POST"; //use POST method when indexing a record without specifying id, and PUT when you specify an id
string jsonEvent = "{\"id\":\"123546789\",\"parentId\":\"abc123\",\"event\":\"CloseAccount\"}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
Console.WriteLine("after get response");
Console.ReadLine();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
I was doing something wrong in my createIndex function but here is my working function incase anyone finds it helpful:
public static void createIndex(string endpoint, string index)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/", endpoint, index));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use PUT method when creating an index
string json = "{\"settings\":{\"activity-log-events\":{\"number_of_shards\":3,\"number_of_replicas\":2}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
You have at least one error in your indexEvent() function. You are setting the string jsonEvent but then using an undefined string json when setting up byteData:
string jsonEvent = "{\"id\":\"123546789\",\"parentId\":\"abc123\",\"event\":\"CloseAccount\"}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
You'll note that you are doing this correctly in the other two functions, using the string json in both places. From createIndex:
string json = "{\"settings\":{\"number_of_shards\":3,\"number_of_replicas\":2}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
and from createMapping:
string json = "{\"activitylogevent\":{\"properties\":{\"id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"parentId\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"event\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
There may be other things wrong in the code but that's definitely not going to work.
I made a some changes to my createIndex function and it worked. I posted the changes above.
Is it possible to pass raw JSON to a Rest API using the Spring RestTemplate?
I am attempting the following:
List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<HttpMessageConverter<?>>();
httpMessageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(httpMessageConverters);
String jsonText = // raw JSON
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> entity = new HttpEntity<Object>(jsonText, httpHeaders);
restTemplate.exchange(url, HttpMethod.POST, entity, responseClass);
When I invoke this request, I get a HTTP 400 error response, meaning bad request. However, all headers and the JSON body are identical as that submitted using a HTTP client I have.
In contrast, the following works fine when I create the MyRequest object and set it on the HttpEntity:
List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<HttpMessageConverter<?>>();
httpMessageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(httpMessageConverters);
MyRequest myRequest = new MyRequest();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> entity = new HttpEntity<Object>(myRequest, httpHeaders);
restTemplate.exchange(url, HttpMethod.POST, entity, responseClass);
Therefore, I am wondering how I can invoke my REST API using raw JSON in String format?
This is Method
String url = String.format("https://SITE");
RestTemplate template = new RestTemplate();
template.getMessageConverters().add(new StringHttpMessageConverter());
String valor ="{\"cmd\":\"123\", \"includeImei\":\"true\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authenticate", "TOKEN");
HttpEntity<String> entity = new HttpEntity<String>(valor, headers);
URI valoresdevueltos = template.postForLocation(url, entity);