Calling an web service from java program - java

I am trying to call an web service by sending an xml file as input and i should be receiving an xml as a reply but whenever i send the xml i get proxy authentication error so i thought i was sending the wrong xml but the same xml works fine when i use SOAP UI so i guess there is some problem with my code.
Here is the code below
URL url = null;
String strUrl="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope\" xmlns:soap=\"SoapAuthenticator\" xmlns:ship=\"http://ws.consignorsupport.no/ShipAdvisor\"><soapenv:Header> <soap:ServiceAuthenticationHeader><soap:Username>TDC43671</soap:Username> <soap:Password>hTiNMft/KaMfDDD</soap:Password><soap:IsEncrypted>false</soap:IsEncrypted></soap:ServiceAuthenticationHeader></soapenv:Header><soapenv:Body><ship:SearchForDropPoints><ship:productConceptID>92</ship:productConceptID><ship:installationID>00000000018</ship:installationID><ship:country>DK</ship:country><ship:address></ship:address><ship:postCode>6000</ship:postCode><ship:city></ship:city><ship:limit>5</ship:limit></ship:SearchForDropPoints></soapenv:Body></soapenv:Envelope>";
String ss="http://www.consignorsupport.no/ShipAdvisor/Main.asmx";
url = new URL(ss);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-type", "text/xml");
conn.setRequestProperty("Accept", "text/xml, application/xml");
conn.setRequestMethod("POST");
conn.connect();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(strUrl);
wr.flush();
wr.close();
int iHttpResponseCode = conn.getResponseCode();
String strErrorMessage = conn.getResponseMessage();
System.out.println("Getting Response status");
System.out.println(iHttpResponseCode);
System.out.println(strErrorMessage);
Can anybode help me as to where i am going wrong.

If you get a proxyauthentication error, chances are that that really is the issue. Maybe soap ui is set up with the correct proxy info? Or gets it from the system settings? Your java code won't automatically pick up on these settings. Check if you have a system proxy configured, or one in soapUI.

Related

HTTP Delete Request on a tomcat server

I'm trying to delete a class given its id number from a tomcat server. I did some research on DELETE request where some sources were saying it's similar to the POST request. So, I changed my code accordingly, however I still get an error code 404.
My controller has a delete mapping with #DeleteMapping("/classes/{cId}") and here's my code to delete a class based on its id number.
URL url = new URL("http://localhost:8080/classes/{cId}");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
OutputStreamWriter wr = new
OutputStreamWriter(connection.getOutputStream());
wr.write("{\"cId\":" + cId + "}");
wr.flush();
wr.close();
connection.connect();
connection.disconnect();
Can someone tell me what I'm doing wrong here? How would I change my code to successfully delete a class?

android sending post request always returns 400 even with correct json string

So I am trying to send a post request to my api using the code below.
When i try the request in fiddler it works. But in android I always get a 400 error.
String url = "http://192.168.1.105:17443/NewUser";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
DataOutputStream os = new DataOutputStream(con.getOutputStream());
String test = user.toJson().toString();
os.writeBytes(test);
os.close();
int responseCode = con.getResponseCode();
Turns out the error I received was a invalid hostname.
I needed to modify my api to allow requests that were not coming from localhost.
you can find more information here:
Connecting to Visual Studio debugging IIS Express server over the lan

HttpUrlConnection method is always GET on android

URL url = new URL("http://myserver.com/myendpoint");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//connection.setRequestMethod("POST") <- this didn't help either
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("string=test");
out.close();
connection.close()
The code above WORKS on desktop JVM, sends a post request, parsed on server-side successfully with response 200, however on android, the request method stays GET (yes I checked it IS false) and results in a 404 exception. Official docs say that setting doOutput to true triggers setting the request method to POST but that doesn't seem the case.
404 is not an exception. It is a HTTP status code returned by the server you make the request to and it means that the url you make the request to is not found. That has nothing to do with POST being set or not.
Things to check:
If the url you are making a request to is right.
If the server has a POST controller/handler mapped to the url you are making the request to.
Ask the guy who develops the server if he is handling the cases right ans if he's sending the correct response codes for the relevant scenarios.
Extra info: if the url is registered on the service but a POST request is not allowed you would get a 415 response code.
When posting data to a server, I'm setting some additional request header:
String query = "string=test";
URL url = new URL("http://myserver.com/myendpoint");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
connection.setFixedLengthStreamingMode(query.getBytes("UTF-8").length);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(query);
But as suggested, the 404 exception usually means, that the endpoint, you're trying to access, isn't available.
Try it:
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");

Google Docs API returns a 503 Service Unavailable when uploading a file. Has something changed?

I have applications that make use of the Google Docs API. Up until recently, uploads using the HTTP endpoints has been working fine. Recently, uploading has suddenly started erroring. The first call to create a session (which returns the resumable URL) works fine, and returns a resumable URL. Attempting to then send the file contents to the resumable URL throws a 503.
The relevant part of the code throwing the error is this:
URL url = new URL(resumableFileUploadUrl);
conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("client_id", OAuth2Client.CLIENT_ID);
conn.addRequestProperty("client_secret", OAuth2Client.CLIENT_SECRET);
conn.setRequestProperty("Authorization", "OAuth " + GetAuthToken());
conn.setRequestProperty("X-Upload-Content-Length", String.valueOf(fileContents.length())); //back to 0
conn.setRequestProperty("X-Upload-Content-Type", "text/xml");
conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length()));
conn.setRequestProperty("Slug", fileName);
if(isUpdate)
{
conn.setRequestProperty("If-Match", "*");
conn.setRequestMethod("PUT");
}
else
{
conn.setRequestMethod("POST");
}
conn.setRequestProperty("GData-Version", "3.0");
conn.setRequestProperty("User-Agent", "GPSLogger for Android");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream());
wr.writeBytes(fileContents);
wr.flush();
wr.close();
int code = conn.getResponseCode();
newLocation = conn.getHeaderField("location");
The above code is used both for creating the session to get the resumable URL as well as posting file contents to the resumable URL.
Which is part of this Android activity. I am including a link to the original activity as it would probably be quite easy to reproduce the problem by simply cloning the repository. The code has remained untouched for a year.
Has something changed recently that would cause this?
I would like to avoid having to use Google Drive's APIs for now as I have not changed any code and the same code is being used in a few of my other applications in the field.
One of the most annoying “features” is the undocumented rate limit when requesting images, each request of which must be authenticated. The rate limit appears to be around 10/s.
You may be using Google API v2 which is deprecated as of now. Read the below post:
https://developers.google.com/google-apps/documents-list/terms

Why do I need getInputStream for HttpUrlConnection to send request?

I have some code that sends a POST request to a PHP script from a Java applet:
String message = URLEncoder.encode(s, "UTF-8");
URL url = new URL(getCodeBase(), "script.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("message=" + message);
out.close();
But this doesn't work in sending the request. I have to add code that calls getInputStream() and reads all of the input for this to work. Why is this? What do I do if I only want to only send a request and not receive one?
You don't, but you do have to call either getInputStream() or getResponseCode(). Otherwise nothing is sent, but also otherwise you don't have any way of knowing whether the call succeeded or not.

Categories