I have spring boot application in which I get the streamName as a parameter, but now I don't want it to work in postman, but in another program in which the streamName is String that is created when calling a function. Previously I was giving it as json, but now I want to give it as parameter and I have no idea how can I do it.
This is my Request in Spring boot:
#PostMapping
#ResponseBody
public String addStream(#RequestParam("streamName") String streamName) {
String key = getRandomHexString();
streamService.addStream(new Stream(streamName,key));
return key;
}
and this is in another program where i want to make this method:
public void onHTTPPostRequest(String streamName) throws IOException {
PostResponse postResponse = new PostResponse();
postResponse.setStreamName(streamName);
Gson gson = new Gson();
String jsonString = gson.toJson(postResponse);
getLogger().info("POST Body " + jsonString);
URL pipedreamURL = new URL("http://10.100.2.44:8080/api?streamName=");
HttpURLConnection conn = (HttpURLConnection) pipedreamURL.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
OutputStream os = conn.getOutputStream();
os.write(jsonString.getBytes("UTF-8"));
os.close();
int responseCode = conn.getResponseCode();
getLogger().info(responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
simply add it to the URL string:
URL pipedreamURL = new URL("http://10.100.2.44:8080/api?streamName=" + streamName);
Related
I am hitting below url using any rest client and I get the api Response :400 Bad Request with response body
INPUT param
POST http://SOME.IP:8008/equipment_api/F0-03-8C-C3-D3-CC/832
HEADERS
Content-Type application/json
X-RequestID 1234
BODY
{
"items":[{"updateValue":1, "updateKey": "RESETDEV"}],
"sync":"false"
}
Response :400 Bad Request
{
"error": "RESETDEV is not a valid key."
}
But java simple client does not show the response body.. below is java code.. it just give 400 bad req.
public static void main(String[] args) {
try {
String urlParameters = " {\r\n" +
"\"items\":[{\"updateValue\":\"Hi\", \"updateKey\": \"RESETDEV\"}],\r\n" +
"\"sync\":false\r\n" +
"}";
URL url = new URL("http://SOME.IP:8008/equipment_api/F0-03-8C-C3-D3-CC/832");
URLConnection conn = url.openConnection();
conn.setRequestProperty("content-type", "application/json");
conn.setRequestProperty("X-RequestID", "1234");
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
}catch(Exception ex) {
System.out.println("some error :: "+ex.toString());
}
}
Try to use following code
final String uri = "http://SOME.IP:8008/equipment_api/F0-03-8C-C3-D3-CC/832";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("X-RequestID", "1234");
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
System.out.println(result);
Wrap with Try Catch.
May it is useful to you. It will work
public static void main(String[] args) {
try {
String urlParameters = " {\r\n" +
"\"items\":[{\"updateValue\":\"Hi\", \"updateKey\":
\"RESETDEV\"}],\r\n" +
"\"sync\":false\r\n" +
"}";
URL url = new URL("http:http://SOME.IP:8008/equipment_api/F0-03-
8C-C3-D3-CC/832");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("content-type", "application/json");
con.setRequestProperty("X-RequestID", "1234");
con.setDoOutput(true);
OutputStreamWriter writer = new
OutputStreamWriter(con.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
//BufferedReader reader = new BufferedReader(new
InputStreamReader(con.getInputStream()));
InputStream is = con.getInputStream();
if(con.getResponseCode() >= 200 && 299 <= con.getResponseCode()) {
is = con.getInputStream();
}else {
is = con.getErrorStream();
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(is,
"utf-8"))) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
writer.close();
// br.close();
}catch(Exception ex) {
System.out.println("some error :: "+ex.toString());
}
}
I have this method to connect to my webservice (REST API)
public static void getHttpCon() throws Exception{
String tokenUrl = AppPropertiesService.getProperty( URL_TOKEN );
String username = AppPropertiesService.getProperty( USERNAME );
String password = AppPropertiesService.getProperty( PASSWORD );
String POST_PARAMS = "username="+username+"&password="+password+"&lang=fr&grant_type=password&client_id=apiclient";
URL obj = new URL(tokenUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json;odata=verbose");
con.setRequestProperty("Authorization",
"Basic Base64_encoded_clientId:clientSecret");
con.setRequestProperty("Accept",
"application/x-www-form-urlencoded");
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
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());
} else {
System.out.println("POST request not worked");
}
}
I want to know how can i POSTa CSV File .
Should I do it directly in my method above ?
Do I have to create a new method by recovering the connection token from my method above?
My API ULR is POST /api/{id}/csv
I've used to MSF4J to get a response by a post request. The code for post request handler is as below.
#Path("/psi")
public class HelloService {
#POST
#Path("/send")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public JSONObject postWithParams(AppParams params) {
String imsi = params.getImsi();
JSONObject json = new JSONObject();
json.put("imsi", imsi);
return json;
}
}
This service is called by another application.It's shown below
String url = "http://localhost:8080/psi/send";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(5000);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
JSONObject msisdn = new JSONObject();
msisdn.put("msisdn", "94773336050");
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(msisdn.toString().getBytes("UTF-8"));
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
When I run both application together the post request gives required out put but same time it shows ERROR MSF4JHttpConnectorListener and that error console output like below.
Error in console ERROR MSF4JHttpConnectorListener
I am using Google Appengine Java endpoints with internal microservices(Modules).
When I execute a call from the endpoints to a module Servlet I receive the X-AppEngine-Inbound-AppId as per documentation(request.getHeader("X-Appengine-Inbound-Appid") and is all good.
When I try to call a module endpoint I don't receive it anymore!!
I am using the same code to execute all the HTTP requests.
public GenericResponse makePOSTRequest(String urlString, Object requestObject, String jSessionId, boolean parseSessionId) {
GenericResponse genericResponse;
String rawPayload = mJsonParser.toJson(requestObject);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", String.valueOf(rawPayload.getBytes("UTF-8").length));
if (jSessionId != null) {
connection.setRequestProperty("Cookie", "JSESSIONID=" + jSessionId);
}
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(rawPayload);
writer.close();
InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
if (!parseSessionId) {
genericResponse = new GenericResponse(connection.getResponseCode(), sb.toString());
} else {
String responseSessionId = parseSessionId(connection);
genericResponse = new GenericResponse(connection.getResponseCode(), sb.toString(), responseSessionId);
}
return genericResponse;
I need to send a post request to a https address. I have a function that sends post messages currectly but i cant seem to make it work for https.
public static String serverCall(String link, String data){
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = data;
try
{
url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after process will be stored in response variable.
response = sb.toString();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
return response;
}
i have tryed using HttpsURLConnection insted of HttpURLConnection, i am still getting null from my server.
you should call connect();
....
connection.setRequestMethod("POST");
connection.connect();
....