How to consume web service rest with java? - java

I have this error:
"Conectando: http://graph.facebook.com/pivotalsoftware
Consulta: {"PARAM1": "pivotalsoftware"}
Error ocurrido
java.io.IOException: Server returned HTTP response code: 403 for URL: http://graph.facebook.com/pivotalsoftware "
and i can't understand it so help me please!
public class Essai {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://graph.facebook.com/pivotalsoftware");
//Insert your JSON query request
String query = "{'PARAM1': 'pivotalsoftware'}";
//It change the apostrophe char to double colon char, to form a correct JSON string
query=query.replace("'", "\"");
try{
//make connection
URLConnection urlc = url.openConnection();
//It Content Type is so importan to support JSON call
urlc.setRequestProperty("Content-Type", "application/xml");
Msj("Conectando: " + url.toString());
//use post mode
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
//send query
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print(query);
Msj("Consulta: " + query);
ps.close();
//get result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String l = null;
while ((l=br.readLine())!=null) {
Msj(l);
}
br.close();
} catch (Exception e){
Msj("Error ocurrido");
Msj(e.toString());
}
}
private static void Msj(String texto){
System.out.println(texto);
// TODO code application logic here
}

Class below should help you
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class userAuthetication {
//5213
public static void userlogin(String usrname, String pwd) throws IOException{
try {
URL url = new URL("http://140.104.135.204:50/Directory-Rest.aspx?Function=Authenticate");
//Insert your JSON query request
String query = "{'Username':'"+ usrname + "',"+ "'Password':'" + pwd + "'}";
//It change the apostrophe char to double colon char, to form a correct JSON string
query=query.replace("'", "\"");
//make connection
URLConnection urlc = url.openConnection();
//It Content Type is so importan to support JSON call
urlc.setRequestProperty("Content-Type", "application/xml");
Msj("Conectando: " + url.toString());
//use post mode
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
//send query
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print(query);
Msj("Consulta: " + query);
ps.close();
//get result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String l = null;
while ((l=br.readLine())!=null) {
Msj(l);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Msj("Error ocurrido");
Msj(e.toString());
}
}
private static void Msj(String texto){
System.out.println(texto);
}
}

While it is possible, I'd not recommend to build your own REST Client (incorporating URLConnection or etc. low-level APIs) unless it's really necessary.
There are several ways to do this. I'll draw your attention on some most popular ones:
Spring's RestTemplate, which uses the Jackson JSON processing library to process the incoming data. (updates with Spring WebClient);
JAX-RS (Jersey implementation), which has several ways to consume different Media Types.
These are the easiest and most popular, performing facilities to create REST Client, hence consume REST Resource.
This is all it takes for RestTemplate to consume REST resource:
public static void getRESTResource() {
final String uri = "your host here;
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class); //note, that there are many overloaded methods for different variations of parameters;
CustomType result = restTemplate.getForObject(REST_URI, CustomType.class, params); //to bind incoming data to your CustomType
}
Example of JAX-RS Client can be found here.

Related

Use java code with REST methods to Send XML Request and Read XML Response from API (Insomnia / SoapUI)

Overview of goals: (1) save XML file to a string element in IntelliJ (2) send the request XML to an http endpoint (3) get the response XML from the http endpoint
So far I have been able to read the XML response but keep receiving errors on my attempts to send a request. I have working methods not implementing the REST methods but would prefer to use those for my project. It's a bit of a rudimentary approach as I am still learning so any tips are greatly appreciated. Would like to be closer to the
My attempts so far have been to set the xml request as a string to send to the endpoint and then read the response from that same endpoint. Below is the code I have attempted that does not yet rely heavily on the REST method. Whenever I try to send the request, I get an error that this method is not allowed. Are there suggestions on my current code I can edit to get this request working?
package com.tests.restassured;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class VIVPXMLResponseTest {
public static void main(String[] args) {
VIVPXMLResponseTest vivpXMLResponseTest = new VIVPXMLResponseTest();
vivpXMLResponseTest.getXMLResponse("Success");
}
public void getXMLResponse(String responseCode) {
String wsURL = "http://localhost:8080/hello/Hello2You";
URL url = null;
URLConnection connection = null;
HttpURLConnection httpConn = null;
String responseString = null;
String outputString = "";
ByteArrayOutputStream bout = null;
OutputStream out = null;
InputStreamReader isr = null;
BufferedReader in = null;
String xmlInputRequest = "<pasteXMLrequestHere>";
try {
url = new URL(wsURL); // create url object using our webservice url
connection = url.openConnection(); // create a connection
httpConn = (HttpURLConnection) connection; // cast it to an http connection
byte[] buffer = new byte[xmlInputRequest.length()]; // xml input converted into a byte array
buffer = xmlInputRequest.getBytes(); // put all bytes into buffer
String SOAPAction = "";
//Set the appropriate HTTP parameters
httpConn.setRequestProperty("Content-Length", String
.valueOf(buffer.length));
httpConn.setRequestProperty("Content-Type",
"text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
//httpConn.setRequestMethod("GET");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
out = httpConn.getOutputStream();
out.write(buffer); // write buffer to output stream
out.close();
//Read response from the server and write it to standard out
isr = new InputStreamReader(httpConn.getInputStream()); //use same http connection, call getInputStream
in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) //read each line
{
outputString = outputString + responseString; //put into string -- may need to change if long file
}
System.out.println(outputString); //print out the string
System.out.println(" ");
//Get response from the web service call
Document document = parseXmlFile(outputString); //parse the XML - gets back raw XML - returns as document object model
NodeList nodeLst = document.getElementsByTagName("ns:Code"); //where success / failure response is written
NodeList nodeLst2 = document.getElementsByTagName("ns:Reason"); //where success / failure response is written
String webServiceResponse = nodeLst.item(0).getTextContent();
String webServiceResponse2 = nodeLst2.item(0).getTextContent();
System.out.println("*** The response from the web service call is : " + webServiceResponse);
System.out.println("*** The reason from the web service call is: " + webServiceResponse2);
} catch (Exception e) {
e.printStackTrace();
}
}
private Document parseXmlFile(String in) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //get document builder factory
DocumentBuilder db = dbf.newDocumentBuilder(); //create new document builder
InputSource is = new InputSource(new StringReader(in)); //pass in input source from string reader
return db.parse(is);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
I'd like to be closer to this format
#Test
#RestAssuredMethod(config = "src/test/resources/config/sampleRest.json")
public void getResponse() throws IOException {
Response response3 = given().log().all()
.when().get("updateFiles/")
.then().assertThat()
.statusCode(HttpStatus.SC_OK) //SC_OK = 200
.body("status[0].model", equalTo("Success"))
.header("Content-Type", containsString("application/json"))
.log().all(true)
.extract().response();
String firstResponse = response3.jsonPath().get("status[0].model");
asserts.assertEquals(firstResponse, "SUCCESS", "Response does not equal SUCCESS");
List allResponses = response3.jsonPath().getList("status[0].model");
System.out.println("**********" + favoriteModels);
asserts.assertTrue(allResponses.contains("Success"), "There are no success responses");
}
Edit: Here is my working send / receive response that I am trying to integrate into using full REST methods:
package com.chillyfacts.com;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Send_XML_Post_Request {
public static void main(String[] args) {
try {
String url = "<enterEndpointHere>";
URL obj = new URL(url);
HttpURLConnection HTTPConnection = (HttpURLConnection) obj.openConnection();
HTTPConnection.setRequestMethod("POST");
HTTPConnection.setRequestProperty("Content-Type","text/xml; charset=utf-8");
HTTPConnection.setDoOutput(true);
String xml = "<pasteXMLRequestHere>"
DataOutputStream writeRequest = new DataOutputStream(HTTPConnection.getOutputStream());
writeRequest.writeBytes(xml);
writeRequest.flush();
writeRequest.close();
String responseStatus = HTTPConnection.getResponseMessage();
System.out.println(responseStatus);
BufferedReader in = new BufferedReader(new InputStreamReader(
HTTPConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("\n **** RESPONSE FROM ENDPOINT RECEIVED ****: \n\n" + response.toString() + "\n\n *************** END OF RESPONSE *************** \n");
} catch (Exception e) {
System.out.println(e);
}
}
}

How to correctly write POST request for a restheart on java

I am using restheart to provide a restful interface to mongodb. Get method is working good, I'm getting data from database in respons. But in this instance I'm trying to implementing POST request to write data in base. I'm running following code but I'm getting response with code 415 unsupported media type. My test base db1 have one collection testcoll where I'm trying to write a document with fields "name" and "rating"
public class PostMethodJava {
public static void main(String[] args) throws IOException {
URL url;
try {
url = new URL("http://127.0.0.1:8080/db1/testcoll/");
//url = new URL("http://google.com/");
} catch (Exception et) {
System.out.println("Data URL is broken");
return;
}
HttpURLConnection hc = null;
try {
hc = (HttpURLConnection) url.openConnection();
String login = "admin:12345678";
final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
final String encoded = Base64.getEncoder().encodeToString(authBytes);
hc.addRequestProperty("Authorization", "Basic " + encoded);
System.out.println("Authorization: " + hc.getRequestProperty("Authorization"));
//hc.setDoInput(true);
hc.setDoOutput(true); //<== removed, otherwise 415 unsupported media type
hc.setUseCaches(false);
hc.setRequestMethod("POST");
//hc.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
hc.setRequestProperty("Accept", "application/json");
} catch (Exception et) {
System.out.println("Can't prepare http URL con");
}
System.out.println(hc.toString());
String parameter = "mame=test1&rating=temp";
int plength = parameter.length();
byte[] pdata = parameter.getBytes(StandardCharsets.UTF_8);
try (DataOutputStream out = new DataOutputStream(hc.getOutputStream())){
out.write(pdata);
}
int rc = hc.getResponseCode();
System.out.println("response code: " + rc);
System.out.println("response message: " + hc.getResponseMessage());
}
}
What is wrong and how can I fix it?
Adding a line:
hc.setRequestProperty("Content-Type","application/json");
and writing the string:
String parameter = "{\"name\":\"doubleabc\",\"rating\":\"allright\"}";
fixed my problem.

Why is my Android app connecting to the Reddit API, but getting a blank response?

I am trying to learn how to connect to an API and receieve and parse JSON data so I am currently following an example on this webpage: http://www.whycouch.com/2012/12/how-to-create-android-client-for-reddit.html, but I am getting an error that says:
E/fetchPosts(): org.json.JSONException: End of input at character 0 of
My app is connecting because it says that a new host connection has been established so I'm not quite sure as to why it's getting a blank response. Below is my class that gets the connection and reads the contents. If I had to guess where I went wrong, I would say it has to do with the request properties, but I went to reddit's website and formatted it like they want and it's still not returning anything. Thank you.
public class RemoteData {
/*
This method returns a connection to the specified URL,
with necessary properties like timeout and user-agent
set to your requirements.
*/
public static HttpURLConnection getConnection(String url){
System.out.println("URL: " + url);
HttpURLConnection hcon = null;
try{
hcon = (HttpURLConnection)new URL(url).openConnection();
hcon.setReadTimeout(30000); //Timeout set at 30 seconds
hcon.setRequestProperty("User-Agent", "android:com.example.reddittestappbydrew:v0.0.1");
}catch(MalformedURLException e){
Log.e("getConnection()", "Invalid URL: " +e.toString());
}catch (IOException e){
Log.e("getConnection()", "Could not connect: " + e.toString());
}
return hcon;
}
/*
A utility method that reads the contents of a url and returns them as a string
*/
public static String readContents(String url){
HttpURLConnection hcon = getConnection(url);
if(hcon == null) return null;
try{
StringBuffer sb = new StringBuffer(8192);
String tmp = "";
BufferedReader br = new BufferedReader(new InputStreamReader(hcon.getInputStream()));
while((tmp = br.readLine()) != null){
sb.append(tmp).append("\n");
}
br.close();
return sb.toString();
}catch(IOException e){
Log.d("READ FAILED", e.toString());
return null;
}
}
}
The code you have written looks pretty naive for getting html/json response data from my URL as redirects are not being handled there. Either you handle redirects in your code which you can do by checking hcon.getResponseCode() whose value should be 200 for you to read the data successfully. In case it is not 200 and something else like 301 (redirects) or 403 (authorization required), you need to handle these responses accordingly.
Here I am giving you a simple code which uses HttpClient (I am using httpclient-4.2.1) library from apache, and gets the response back as String.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.fileupload.util.Streams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpUtils {
private static Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);
public static String getResponse(String url) throws IOException {
return getResponse(url, "UTF-8");
}
public static String getResponse(String url, String characterEncoding) throws IOException {
return getByteArrayOutputStream(url).toString(characterEncoding);
}
public static byte[] getBytes(String url) throws IOException {
return getByteArrayOutputStream(url).toByteArray();
}
public static ByteArrayOutputStream getByteArrayOutputStream(String url) throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpclient.execute(httpGet);
LOGGER.debug("Status Line: " + response.getStatusLine());
HttpEntity resEntity = response.getEntity();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Streams.copy(resEntity.getContent(), byteArrayOutputStream, true);
return byteArrayOutputStream;
}
public static void main(String[] args) throws IOException {
System.out.println(getResponse("https://www.reddit.com/r/AskReddit/.json"));
}
}
Use this code to achieve what you want and in case you don't want to use HTTPClient API, then modify your existing code to handle http status codes but it would be simple for you to use above code.

GWT Error: "The output stream has been committed and can no longer be written to"

New to Java and GWT. Here is my problem. I am getting this error message: "The OutputStream has been committed and can no longer be written to." while I am trying to post xml to a remote server via REST API.
It is happening on this line in the code below:
out.write("Content-Type: application/x-www-form-urlencoded\r\n");
This works from terminal:
curl -d "OPERATION_NAME=ADD_REQUEST&TECHNICIAN_KEY=DxxxxxxxxxxxxxxxxxxxB6&INPUT_DATA=<?xml version=%221.0%22 encoding=%22utf-8%22?><Operation><Details><requester>Me</requester><subject>Test</subject><description>Testing curl input again</description></Details></Operation>" http://app.company.com/sdpapi/request/
I'm having trouble translating the above curl command into the code below. I got the following code from a tutorial and I'm not sure how to pass in the URL and parameters properly. Any suggestions or additional methods of troubleshooting will be appreciated. I did not find much of anything on google for this.
package com.gwt.HelpDeskTest.server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.gwt.HelpDeskTest.client.HelpDeskTestService;
import com.gwt.HelpDeskTest.shared.HelpDeskTestException;
#SuppressWarnings("serial")
public class HelpDeskTestImpl extends RemoteServiceServlet implements
HelpDeskTestService {
#Override
public String getFromRemoteServer(String serviceUrl)
throws HelpDeskTestException {
String result = "";
try {
final URL url = new URL(serviceUrl);
final BufferedReader in= new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine= in.readLine()) != null) {
result+= inputLine;
}
in.close();
return result;
} catch (final Exception e) {
throw new HelpDeskTestException();
}
}
#Override
public String postToRemoteServer(String serviceUrl)
throws HelpDeskTestException {
try {
final String serverHost= "http://app.company.com/";
final String serverPath= "http://app.company.com/sdpapi/request/";
final String serverParameters=
"OPERATION_NAME=ADD_REQUEST&TECHNICIAN_KEY=Dxxxxxxxxxx6&INPUT_DATA=%3C?xml%20version=%25221.0%2522%20encoding=%2522utf-8%2522?%3E%3COperation%3E%3CDetails%3E%3Crequester%3EMe%3C/requester%3E%3Csubject%3ETest%3C/subject%3E%3Cdescription%3ETesting%20GWT%20input%20again%3C/description%3E%3C/Details%3E%3C/Operation%3E"; //put parameters here for testing.
final URL url = new URL(serverHost);
final URLConnection connection= url.openConnection();
connection.setDoOutput(true);
connection.setConnectTimeout(10000); //added this to see if I can address the timeout issue.
connection.setReadTimeout(10000);
final OutputStreamWriter out= new OutputStreamWriter(connection.getOutputStream());
final BufferedReader in= new BufferedReader(new InputStreamReader(
connection.getInputStream()));
out.write("POST " + serverPath + "\r\n");
out.write("Host: " + serverHost + "\r\n");
out.write("Accept-Encoding: identity\r\n");
out.write("Connection: close\r\n");
out.write("Content-Type: application/x-www-form-urlencoded\r\n"); //This is where the error is occuring
out.write("Content-Length: " + serverParameters.length() + "\r\n\r\n" +
serverParameters + "\r\n");
String result = "";
String inputLine;
while ((inputLine=in.readLine()) != null) {
result+= inputLine;
}
in.close();
out.close();
return result;
} catch (final Exception e) {
System.out.println(e.getMessage());
throw new HelpDeskTestException();
}
}
}
I think it would be easier for you to use an HttpURLConnection instead of a plain URLConnection. It has convenience methods to set the headers and other properties. See the accepted answer to this question for a good example of how to use it to do a POST:
Java - sending HTTP parameters via POST method easily

consuming SOAP web service in java

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();

Categories

Resources