I need to access a .Net SOAP Service manually. All the importers have issues with its WSDL, so I'm just manually creating the XML message, using HttpURLConnection to connect, and then parsing the results. I've wrapped the Http/SOAP call into a function that is supposed to return the results as a string. Here's what I have:
//passed in values: urlAddress, soapAction, soapDocument
URL u = new URL(urlAddress);
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("SOAPAction", soapAction);
connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
connection.setRequestProperty("Accept","[star]/[star]");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
//helper function that gets a string from a dom Document
String xmldata = XmlUtils.GetDocumentXml(soapDocument);
wout.write(xmldata);
wout.flush();
wout.close();
// Response
int responseCode = connection.getResponseCode();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseString = "";
String outputString = "";
//Write the SOAP message response to a String.
while ((responseString = rd.readLine()) != null) {
outputString = outputString + responseString;
}
return outputString;
My problem is on the line BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); I get a "java.io.FileNotFoundException" with the address that I'm using (i.e. urlAddress). If I paste that address into a browser, it pulls up the Soap Service webpage just fine (address is http://protectpaytest.propay.com/API/SPS.svc). From what I've read, the FileNotFoundException is if the HttpURLConnection returns a 400+ error message. I added the line getResponseCode() just to see what the exact code was, and it's 404. I added the User-Agent and Accept headers from some other pages saying they were needed, but I'm still getting 404.
Are there other headers I'm missing? What else do I need to do to get this call to work (since it works in a browser)?
-shnar
Related
I'm using HttpURLConnection to send a POST request to get the access token. However, I get the error says
java.io.IOException: Server returned HTTP response code: 401 for URL: https://xyz.auth0.com/oauth/token
Note: I'm able to get the access token via Postman.
Can someone please help me? Thanks in advance!
public String requestToken() throws Exception{
StringBuilder response = new StringBuilder();
URL url = new URL("https://xyz.auth0.com/oauth/token");
//open a connection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//set the request method
connection.setRequestMethod(TokenConstant.METHOD_POST);
//set the request content-type header parameter
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
//set response format type
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
//create request parameter
String jsonInputString = "grant_type=client_credentials&client_id=xyz&client_secret=abc&audience=https://xyz.abc.com}";;
// we need to write it
try(OutputStream outputStream = connection.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
//Read the response from Input Stream
//get the input stream to read the response content
try(BufferedReader br = new BufferedReader(
new InputStreamReader(
connection.getInputStream(),"utf-8"))){
String responseLine = null;
while((responseLine = br.readLine()) != null){
response.append(responseLine.trim());
}
}
return response.toString();
}
Sample curl facebook oauth access token generation (GET request) - To generate an app access token:
curl -X GET "https://graph.facebook.com/oauth/access_token
?client_id={your-app-id}
&client_secret={your-app-secret}
&grant_type=client_credentials"
Commented few headers - Not required. Changed request to GET.
NOTE: if it works fine with curl, then your code might work fine, with few modifications.
public static String requestToken() throws Exception{
StringBuilder response = new StringBuilder();
URL url = new URL("https://graph.facebook.com/oauth/access_token");
//open a connection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//set the request method
connection.setRequestMethod("GET");
//set the request content-type header parameter
// Commented - not required
/*connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");*/
//set response format type
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
//create request parameter
String jsonInputString = "client_id=<your-app-id>&client_secret=<your-app-secret>&grant_type=client_credentials";;
// we need to write it
try(OutputStream outputStream = connection.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
//Read the response from Input Stream
//get the input stream to read the response content
try(BufferedReader br = new BufferedReader(
new InputStreamReader(
connection.getInputStream(),"utf-8"))){
String responseLine = null;
while((responseLine = br.readLine()) != null){
response.append(responseLine.trim());
}
}
return response.toString();
}
Am trying to create a JAVA GET Http connection request with JSON Array data as shown below. where as the same code works with out any parameter (i.e. ?data={..})
String myurl = "https://myserver.com/test/api/v1/parameter?data={"username":{"name":"testusername"},"salary":{"sal":"56748","bonus":"3221"},"category":{"cat":"CATA"}}";
String newmyurl = myurl.replaceAll("\"","\\\"");
log.info("**newmyurl*** "+newmyurl);
URL url = new URL(newmyurl);
log.info("**URL*** "+url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// By default it is GET request
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode(); // Code breaks here nothing errors in log
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String output;
StringBuffer sb = new StringBuffer();
while ((output = in.readLine()) != null) {
sb.append(output);
}
in.close();
//printing result from response
log.info("****return string****"+sb.toString());
To escape characters in a URL, use URLEncoder:
String myjson = "{\"username\":{\"name\":\"testusername\"},\"salary\":{\"sal\":\"56748\",\"bonus\":\"3221\"},\"category\":{\"cat\":\"CATA\"}}";
String myurl = "https://myserver.com/test/api/v1/parameter?data=" + URLEncoder.encode(myjson, "UTF-8");
I need to send a post request to url which is formed as follows:
www.abc.com/service/postsomething?data={'name':'rikesh'}&id=45
Using HttpPost client in java, how can post request to such query strings
I could connect from javascript easily through ajax but from java client, it's failing.
(I know sending querystring in post request is stupid idea. Since I am connecting to someone else's server I cannot not change the way it is)
Here is one way to send JSON in a POST request using Java (without Apache libraries). You might find this helpful:
//init
String json = "{\"name\":\"rikesh\"}";
String requestString = "http://www.example.com/service/postsomething?id=45";
//send request
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
os.flush();
int responseCode = conn.getResponseCode();
//get result if there is one
if(responseCode == 200) //HTTP 200: Response OK
{
String result = "";
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while((output = br.readLine()) != null)
{
result += output;
}
System.out.println("Response message: " + result);
}
i'm trying to run a soap request in a basic http request...naturally i tried with external tools the message and is correct, like the endpoint i'm using as targetUrl, the wsdl is in something like
http://00.00.00.00/a-ws/services/basic?wsdl
and my actual end point is
http://00.00.00.00/a-ws/services/basic.targetservice
and i'm using this last as target url
URL url = new URL(targetUrl);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
connection.setRequestProperty("SOAPAction", action);
connection.setRequestProperty("User-Agent", "myagent");
connection.setRequestProperty("Host", "localhost");
//connection.setRequestProperty("Content-Length", "" + Integer.toString(message.getBytes().length));
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
OutputStream wr = connection.getOutputStream ();
wr.write (message.getBytes());
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line=null;
StringBuffer response = new StringBuffer();
while( (line = rd.readLine()) != null) {
if (line!=null)
response.append(line);
}
rd.close();
return response.toString();
the raw message is tested with chrome plugin, the only thing i can't test is headers but the result is always an exception on getInputStream
java.io.IOException: Server returned HTTP response code: 500 for URL:
why?
It was a very stupid issue of encoding (like I was supposing)...i didn't escape double quote inside the message.
The evidence of problem was visible using a fake http server that just echo contents.
UPDATE:
Another thing nobody already pointed out is that is useful in case of exception to retrieve
connection.getErrorStream()
that contains the response in case of error!
I'm submitting the request below in Java via a Websphere Portlet.
It works fine when I submit manually using postman (chrome extension) but cannot get it to succeed via java.
What am I missing?
I imported the SSL cert from remote host into Websphere, so SSL connections are not the issue.
Exception in logs ..
[7/15/14 23:06:39:993 BST] 00000170 ServletWrappe E com.ibm.ws.webcontainer.servlet.ServletWrapper service CWSRV0014E: Uncaught service() exception root cause MyApp: java.io.IOException: Server returned HTTP response code: 500 for URL: https://server.com/msg
This is the java code invoking the request and trying to read the response ..
URL url = new URL("https://server.com/msg");
URLConnection connection = url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String body = URLEncoder.encode("{\"x\": \"hello\"}", "UTF-8");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(body);
out.close();
// Exception occurs here ..
BufferedReader rd2 = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = rd2.readLine()) != null) {
result += line;
}
rd2.close();
This was solution, to not URLEncoder.encode() the POST body ..
URL url = new URL(queries.getQuery(sessionBean.getSelectedQuery()));
URLConnection connection = url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String json = "{\"x\": \"hello\"}";
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(json);
out.close();
BufferedReader rd2 = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = rd2.readLine()) != null) {
result += line;
}
rd2.close();