I have POST API endpoint in Java , which is like below which is to be called for storing student marksheet in the portal.
POST API endpoint
/**
#param name
Name of student
#param class
Class of student
#param section
Section of student
#param rollno
Roll Number of student
#param file
Marksheet of student in .xlsx format
**/
#PostMapping(value="/storeMarksheet", produces = "application/json")
public String performTaskAndSendResponse(
#RequestParam String name,
#RequestParam String class,
#RequestParam String section,
#RequestParam String rollno,
#RequestPart(name=file) #ApiParam(".xlsx file") MultipartFile file
){
System.out.println("Inside store marksheet endpoint") // not getting printed
// Store marksheet and return response accordingly
}
And have written a function like below to call it
POST API function call
public String postAPI(String name, String class, String section, String rollno, MultipartFile marksheet){
Map<String, Object> student = new HashMap<String, Object>;
student.put("name", name);
student.put("class", class);
student.put("section", section);
student.put("rollno", rollno);
student.put("file", marksheet);
String dataAsString = student.toString();
String API = "https://somedomain.com/example/storeMarksheet";
StringBuilder resp = new StringBuilder();
String lineResponse = null;
try{
URL url = new URL(API);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Using HttpURL connection
conn.setRequestMethod("POST");
conn.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(dataAsString.getBytes("utf-8"));
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
while((lineResponse = br.readLine()) != null) resp.append(lineResponse.trim());
System.out.println(resp.toString());
return resp;
}catch(Exception e){
return null;
}
}
However seems like the call is not going at all.
Using HttpURLConnection for making http calls.
NOTE
First priority is sending via HttpURLConnection only, if impossible
then open to other solutions
The above POST API endpoint is working perfectly in swagger.
Tried to do via HttpURLConnection but nothing worked for me. Therefore posting answer using another process
public String postAPI(String name, String class, String section, String rollno, MultipartFile marksheet){
String responseStr = null;
try{
HttpPost req = new HttpPost("https://somedomain.com/example/storeMarksheet");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("name",name);
builder.addTextBody("class",class);
builder.addTextBody("section",section);
builder.addTextBody("rollno",rollno);
builder.addbinaryBody("file", marksheet.getBytes(), ContentType.DEFAULT_BINARY, marksheet.getOriginalFilename() );
HttpEntity entity = builder.build();
req.setEntity(entity);
CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse res = client.execute(req);
responseStr = EntityUtils.toString(res.getEnity().toString());
System.out.println(responseStr);
return responseStr;
}catch(Exception e){
//do something.. have put common exception for now
return null;
}finally{
try{
res.close();
client.close();
}catch(Exception e){
//do something.. have put common exception for now
}
}
}
Related
Here is my code
private static final String MEDIA_TYPE = "application/json";
private static final String FORMAT = "UTF-8";
private static String baseServiceUrl;
private static String apiServiceUrl;
#RequestMapping("/")
public ResponseEntity<?> getMessage() throws Exception {
logger.info("Started");
try {
messageProcessor.getMessage("test service");
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
StringRequestEntity requestEntity = null;
HttpClient httpclient = new HttpClient();
int statusCode;
logger.info("RequestBody"+data);
baseServiceUrl="http://localhost:8080/services";
apiServiceUrl="/services/rest/json";
StringBuffer eventResponse = new StringBuffer();
requestEntity = new StringRequestEntity(data, MEDIA_TYPE, FORMAT);
PostMethod postMethod = new PostMethod(baseServiceUrl+apiServiceUrl);
postMethod.setRequestEntity(requestEntity);
statusCode = httpclient.executeMethod(postMethod);
logger.info("Status code"+statusCode);
}
catch (Exception ex) {
logger.error("Exception occurs ", ex);
return new ResponseEntity("Internal server error !!", HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity("Successfully called the service!!", HttpStatus.OK);
}
I want to get the requestbody of one API and send to another API .And a json is my request body.But in this code,I got the status code as 400.Can anyone help me to solve the problem
I think you have appended the /services in the url twice. It should be like:
baseServiceUrl="http://localhost:8080/services";
apiServiceUrl="/rest/json";
In your code you are reading the request body as a string , could you share the request body that is logged.The HTTP response code 400 corresponds to BAD request . So probably, either the endpoint that you are trying to hit is different or the request body has an issue. Try removing the /services from your apiServiceUrl to correct the url path.Also, since you are most probably having a json as request body try the following approach :
String json = "{"id":1,"name":"xxxx"}";
StringEntity entity = new StringEntity(json);
postMethod.setEntity(entity);
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
make sure that the string that you read from the request using BufferedReader reader = request.getReader(); is in appropriate json format.
import java.net.*;
import java.io.*;
public class sample
{
public static void main (String args[])
{
String line;
try
{
URL url = new URL( "http://localhost:8080/WeighPro/CommPortSample" );
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
line = in.readLine();
System.out.println( line );
in.close();
}
catch (Exception e)
{
System.out.println("Hello Project::"+e.getMessage());
}
}
}
My Servlet is invoking another Jsp page like the below,
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
I am not getting any reaction/output in the browser, where the servlet has to be executed once it is invoked.
Am I missing any basic step for this process? Please Help!!!
If you want to open it in browser try this
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://localhost:8080/WeighPro/CommPortSample"));
You question is not clear. Do you actually want to invoke a Servlet from the Main method, or do you want to make an HTTP request to your web application?
If you want to make an HTTP request, I can't see any obvious problems with your code above, which makes me believe that the problem is in the Servlet. You also mention that you don't get anything in the browser, but running your program above does not involve a browser.
Do you mean that you don't get a response when you go to
http://localhost:8080/WeighPro/CommPortSample
in a browser?
As Suresh says, you cannot call a Servlet directly from a main method.
Your Servlet should instead call methods on other classes, and those other classes should be callable from the main method, or from Test Cases. You need to architect your application to make that possible.
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class OutBoundSimul {
public static void main(String[] args) {
sendReq();
}
public static void sendReq() {
String urlString = "http://ip:port/applicationname/servletname";
String respXml = text;
URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter out = null;
BufferedInputStream inputStream = null;
try {
System.out.println("URL:"+urlString);
url = new URL(urlString);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
System.out.println("SendindData");
out = new OutputStreamWriter(urlConnection.getOutputStream());
System.out.println("Out:"+out);
out.write(respXml);
out.flush();
inputStream = new BufferedInputStream(urlConnection.getInputStream());
int character = -1;
StringBuffer sb = new StringBuffer();
while ((character = inputStream.read()) != -1) {
sb.append((char) character);
}
System.out.println("Resp:"+sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Invoking Servlet with query parameters Form Main method
Java IO
public static String accessResource_JAVA_IO(String httpMethod, String targetURL, String urlParameters) {
HttpURLConnection con = null;
BufferedReader responseStream = null;
try {
if (httpMethod.equalsIgnoreCase("GET")) {
URL url = new URL( targetURL+"?"+urlParameters );
responseStream = new BufferedReader(new InputStreamReader( url.openStream() ));
}else if (httpMethod.equalsIgnoreCase("POST")) {
con = (HttpURLConnection) new URL(targetURL).openConnection();
// inform the connection that we will send output and accept input
con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST");
con.setUseCaches(false); // Don't use a cached version of URL connection.
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
con.setRequestProperty("Content-Language", "en-US");
DataOutputStream requestStream = new DataOutputStream ( con.getOutputStream() );
requestStream.writeBytes(urlParameters);
requestStream.close();
responseStream = new BufferedReader(new InputStreamReader( con.getInputStream(), "UTF-8" ));
}
StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
String line;
while((line = responseStream.readLine()) != null) {
response.append(line).append('\r');
}
responseStream.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace(); return null;
} finally {
if(con != null) con.disconnect();
}
}
Apache Commons using commons-~.jar
{httpclient, logging}
public static String accessResource_Appache_commons(String url){
String response_String = null;
HttpClient client = new HttpClient();
GetMethod method = new GetMethod( url );
// PostMethod method = new PostMethod( url );
method.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
method.setQueryString(new NameValuePair[] {
new NameValuePair("param1","value1"),
new NameValuePair("param2","value2")
}); //The pairs are encoded as UTF-8 characters.
try{
int statusCode = client.executeMethod(method);
System.out.println("Status Code = "+statusCode);
//Get data as a String OR BYTE array method.getResponseBody()
response_String = method.getResponseBodyAsString();
method.releaseConnection();
} catch(IOException e) {
e.printStackTrace();
}
return response_String;
}
Apache using httpclient.jar
public static String accessResource_Appache(String url) throws ClientProtocolException, IOException{
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
URIBuilder builder = new URIBuilder( url )
.addParameter("param1", "appache1")
.addParameter("param2", "appache2");
HttpGet method = new HttpGet( builder.build() );
// HttpPost method = new HttpPost( builder.build() );
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
#Override
public String handleResponse( final HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
return "";
}
};
return httpclient.execute( method, responseHandler );
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
JERSY using JARS {client, core, server}
public static String accessResource_JERSY( String url ){
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource( url );
ClientResponse response = service.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
if (response.getStatus() != 200) {
System.out.println("GET request failed >> "+ response.getStatus());
}else{
String str = response.getEntity(String.class);
if(str != null && !str.equalsIgnoreCase("null") && !"".equals(str)){
return str;
}
}
return "";
}
Java Main method
public static void main(String[] args) throws IOException {
String targetURL = "http://localhost:8080/ServletApplication/sample";
String urlParameters = "param1=value11¶m2=value12";
String response = "";
// java.awt.Desktop.getDesktop().browse(java.net.URI.create( targetURL+"?"+urlParameters ));
// response = accessResource_JAVA_IO( "POST", targetURL, urlParameters );
// response = accessResource_Appache_commons( targetURL );
// response = accessResource_Appache( targetURL );
response = accessResource_JERSY( targetURL+"?"+urlParameters );
System.out.println("Response:"+response);
}
Simply you cannot do that.
A response and request pair will generated by web container. You cannot generate a response object and send to the browser.
By the way which client/browser you are expecting to get the response ? No idea. Right ?
When container receives a request from client then it generates response object and serves you can access that response in service method.
If you want to see/test the response, you have to request from there.
i made a HttpUrlConnection GET in Java. And takes a lot to process, the code makes a GET to a URL that returns a JSON. (Which is not that huge, just a couple of rows) Don't know why is taking like A LOT to process from a jQuery ajax call client-side.
This is the Java code:
#RequestMapping(value = "/getchartdata", method = RequestMethod.GET)
public ResponseEntity<String> graphChartData(ModelMap model, HttpServletRequest request) {
String graphName = request.getParameter("graphName");
String subgroup = request.getParameter("subgroup");
HttpURLConnection connection = null;
try {
String configURL = EsbConfig.getProperty("graph.url", "http://localhost:8081");
URL url = new URL(configURL + "/plot/get?graphName="+ graphName+"&subgroup="+subgroup+"&width=100");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
StringBuilder responseData = new StringBuilder();
while((line = in.readLine()) != null) {
responseData.append(line);
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(responseData.toString(), responseHeaders, HttpStatus.CREATED);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if(null != connection) { connection.disconnect(); }
}
return null;
}
I won't add the ajax call since it's pretty plane and simple, nothing to say about that.
If i access directly with the entire URL, i get the json response in nano seconds. If i make the call from client-side, it takes like 10 seconds to retrieve the info.
Any ideas on what's wrong? or any other HTTP get i could implement?
Thanks.
I've created a web crawler using Java and Playframework 1.2.3.
Now, i'd like to crawl some webpages protected by a classic login/password form.
In fact, it's like doing this play test :
#Test
public void someTestOfASecuredAction() {
Map<String, String> loginUserParams = new HashMap<String, String>();
loginUserParams.put("username", "admin");
loginUserParams.put("password", "admin");
Response loginResponse = POST("/login", loginUserParams);
Request request = newRequest();
request.cookies = loginResponse.cookies; // this makes the request authenticated
request.url = "/some/secured/action";
request.method = "POST";
request.params.put("someparam", "somevalue");
Response response = makeRequest(request);
assertIsOk(response); // Passes!
}
But not with the site generated by play, but with an external website.
So, i manage to use play web server to do that :
Map<String,String> params = new HashMap<String, String>();
params.put( "telecom_username",
Play.configuration.getProperty("telecom.access.user") );
params.put( "telecom_password",
Play.configuration.getProperty("telecom.access.pass") );
HttpResponse response = WS.url(loginUrl)
.setParameters(params)
.followRedirects(true)
.post();
When i'm doing that, if i look in response.getString(), i found the redirection page where cookies are set before continuing, but then, if i get a protected page, i'm still not log in. It's like the cookies were never set, and the HttpResponse object does not have any cookies related function, like the response in previous test code.
I've also tried the authenticate() method on ws.url() but it doesn't work either.
I don't really know if what i'm trying to do is possible by using play web server, but i could use an help on this ^^
Thanks a lot !
Ok, I found a way to do it, but I did it the hard way, here it is:
First, the GET, where we store the session cookies, please take into account the charset that I'm using and that I knew the name of the cookie I was looking for, you could store them all. Also, you may want to encrypt them.
HttpResponse wsResponse = WS.url(comercialYComunUrl).get();
String responseString = wsResponse.getString("ISO-8859-1");
if (wsResponse.getStatus() == 200) {
List<Header> headers = wsResponse.getHeaders();
// get all the cookies
List<String> cookies = new ArrayList<String>();
for (Header header: headers) {
if (header.name.equals("Set-Cookie")) {
cookies = header.values;
}
}
// look for the session cookies
String sessionCookie = "";
for (String cookie : cookies) {
if (cookie.toUpperCase().contains("ASPSESSIONID")) {
sessionCookie = cookie.split(";", 2)[0];
}
}
// store it on the session
session.put("COOKIE", sessionCookie);
}
An now the Post:
String url = "http://www.url.com/";
String charset = "ISO-8859-1";
String param1 = "value1";
String param2 = "value2";
String param3 = "value3";
String query = String.format("param1=%s¶m2=%s¶m2=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset),
URLEncoder.encode(param3, charset));
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
connection.addRequestProperty("Cookie", session.get("COOKIE"));
OutputStream output = null;
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}
InputStream responseStream = connection.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(responseStream, writer);
String response = writer.toString();
And that worked for me, this is my source, it's a great post:
How to use java.net.URLConnection to fire and handle HTTP requests?
----------------------------EDIT-------------------------------------
Ok, I wan't all that happy with the answer, so I found a better way:
String url = "http://www.url.com/";
String charset = "ISO-8859-1";
String param1 = "value1";
String param2 = "value2";
String param3 = "value3";
WSRequest wsRequest = WS.url(url);
wsRequest.parameters.put("param1", param1);
wsRequest.parameters.put("param2", param2);
wsRequest.parameters.put("param3", param3);
wsRequest.headers.put("Cookie", session.get("COOKIE"));
HttpResponse wsResponse = wsRequest.post();
String responseString = wsResponse.getString(charset);
And it works ^.^
I am looking for some alternatives of consuming a SOAP web service in java. I am currently using a stub method to consume it and it's too simple for my instructor needs. My instructor said to do a trivial client, what was that suppose to mean?
SOAP is basically the submission of XML to a web server using the POST method. While the XML can get verbose, you should be able to construct the XML using StringBuilder and then use a simple HTTP client, like the Apache HttpClient to construct a POST request to a URL using
the XML string as the body.
That's about as simple as they come.
Here is the simple and lightweight example for consuming the soap api. Steps are below.
You must create the SOAPTestController.java, KflConstants.java And SoapClient.java class.
Then Implement the below code blocks and enjoy it.
Here is the SOAPTestController.java class
#Controller
public class SOAPTestController {
#RequestMapping(value = "/showdate", method = RequestMethod.GET)
public #ResponseBody String getDateAndTime() {
String DateAndTimeSOAPRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
+ "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\r\n"
+ " <soap12:Body>\r\n" + " <GetDateAndTime xmlns=\"http://tempuri.org/\" />\r\n"
+ " </soap12:Body>\r\n" + "</soap12:Envelope>";
String Fundtion = "GetDateAndTime";
return new SoapClient().ConsumeTheService(DateAndTimeSOAPRequest, "GetDateAndTime");
}
}
This is the KflConstants.java class
public class KflConstants {
public static final String SERVER_IP = "http://192.168.0.222/";
public static final String SERVICE_URL = SERVER_IP + "businesswebserviceNew/service.asmx";
public static final String CONTENT_TYPE_TEXT_XML = "text/xml; charset=utf-8";
public static final String GET_DATE_AND_TIME_URL = SERVICE_URL + "/GetDateAndTime";
}
Here is the SOAPClient.java class
public class SoapClient {
private static Logger log = LogManager.getLogger(SoapClient.class);
/*Input Stream Convert to the String Object*/
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
public String ConsumeTheService(String SOAPXML, String APINAME) {
String Result = null;
try {
/*Create The Connection*/
URL url = new URL(KflConstants.SERVICE_URL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", KflConstants.CONTENT_TYPE_TEXT_XML);
conn.setRequestProperty(APINAME, KflConstants.GET_DATE_AND_TIME_URL);
log.info("Sending the envelope to server");
/*Send the request XML*/
OutputStream outputStream = conn.getOutputStream();
outputStream.write(SOAPXML.getBytes());
outputStream.close();
/* Read the response XML*/
log.info("Reading the Response");
InputStream inputStream = conn.getInputStream();
Result = convertStreamToString(inputStream);
inputStream.close();
/*INput Stream Convert to the SOAP Message*/
InputStream is = new ByteArrayInputStream(Result.getBytes());
SOAPMessage resposeSOAP = MessageFactory.newInstance().createMessage(null, is);
/*Return Values*/
log.info("Result SOAP:"+resposeSOAP.toString());
log.info("Result String:"+Result);
return Result;
} catch (Exception e) {
e.printStackTrace();
log.error(e);
return e.toString();
}
}
Thanks,
SoapRequestBuilder s = new SoapRequestBuilder();
s.Server = "127.0.0.1"; // server ip address or name
s.MethodName = "ConcatWithSpace";
s.XmlNamespace = "http://tempuri.org/";
s.WebServicePath = "/SimpleService/Service1.asmx";
s.SoapAction = s.XmlNamespace+s.MethodName;
s.AddParameter("one", "David");
s.AddParameter("two", "Hobbs");
String response = s.sendRequest();