java getting incomplete soap response - java

In my project I am calling a web service by the sending soap request in this format,
try {
URL u = new URL(server);
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("SOAPAction", SOAP_ACTION);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "text/xml; charset=utf-8");
String xmldata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"+
"<soap:Body>"+
"<GetAllCars xmlns=\"http://parkinghero.com/\">"+
"<clsGetAllCarsRequest>"+
"<clsCredentials>"+
"<EmailAddress>"+Email+"</EmailAddress>"+
"<Password>"+passWRD+"</Password>"+
"<TokenID>"+token+"</TokenID>"+
"</clsCredentials>"+
"</clsGetAllCarsRequest>"+
"</GetAllCars>"+"</soap:Body>"+
"</soap:Envelope>";
System.out.println(xmldata);
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
wout.write(xmldata);
wout.flush();
wout.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//InputStream in = connection.getInputStream();
String result;
//int c;
while ((result=rd.readLine()) != null) {
System.out.println(result);
int length = result.length();
String jsonObj = result.substring(294, (length - 74));
System.out.println(jsonObj);
}rd.close();
}
catch (IOException e)
{
System.out.println("in Exception called");
System.err.println(e);
}
For this request the response will be json array
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetAllCarsResponse xmlns="http://abcd.com/">
<GetAllCarsResult>
{"clsError":{"ErrorCode":306,"ErrorDescription":"Data Available"},
"CarsArray":[{"CarID":1,"UserID":1,"RegisteredOwner":"Suresh thorata","Make":"Esteem","Model":"23434","Color":"Brownd","BodyType":"Normal","PlateType":"COM",
"PlateNumber":"WAG1PM","State":"NY","VINNumber":"000000000000","YearOfRegistration":2000,"ExpiryDate":"10/25/2014 4:24:57 PM",
"IsDeleted":true,"DateAddedTimeStamp":"10/18/2010 10:19:04 AM","LastUpdatedTimeStamp":"10/25/2010 4:24:57 PM"},
{"CarID":2,"UserID":1,"RegisteredOwner":"Balaji","Make":"Land Rover","Model":"9999","Color":"Brown","BodyType":"Normal","PlateType":"PAS","PlateNumber":"WAG2PM",
"State":"NY","VINNumber":"","YearOfRegistration":2003,"ExpiryDate":"10/18/2014 11:01:07 AM","IsAutoFightOn":true,"IsDeleted":true,"DateAddedTimeStamp":"10/18/2010
11:01:07 AM","LastUpdatedTimeStamp":"10/18/2010 11:01:07 AM"},
{"CarID":3,"UserID":1,"RegisteredOwner":"Suresh","Make":"Dodge","Model":"5670","Color":"Brown","BodyType":"Normal","PlateType":"AYG","PlateNumber":"WAG3PM",
"State":"NY","VINNumber":"","YearOfRegistration":2000,"ExpiryDate":"10/18/2014 11:01:39 AM","IsDeleted":true,"DateAddedTimeStamp":"10/18/201
0 11:01:39 AM","LastUpdatedTimeStamp":"12/9/2010 11:36:14 PM"},
{"CarID":4,"UserID":1,"RegisteredOwner":"Suresh Babu","Make":"Infiniti","Model":"234353","Color":"Brownd","BodyType":"Normal","PlateType":"PAS",
"PlateNumber":"WAG4PM","State":"NY","VINNumber":"000000000000","YearOfRegistration":2000,"ExpiryDate":"10/20/2014 1:01:22 PM","IsAutoFightOn":true,
"IsDeleted":true,"DateAddedTimeStamp":"10/20/2010 1:01:22 PM","LastUpdatedTimeStamp":"12/3/2010 12:20:29 PM"},{"CarID":5,"UserID":1,
"RegisteredOwner":"Suresh1 thorata","Make":"Esteem","Model":"23434","Color":"Brownd","BodyType":"Normal","PlateType":"COM",
"PlateNumber":"WAG5PM","State":"NY","VINNumber":"000000000000","YearOfRegistration":2000,"ExpiryDate":"10/25/2014 11:44:06 AM"
,"IsDeleted":true,"DateAddedTimeStamp":"10/25/2010 11:39:00 AM","LastUpdatedTimeStamp":"10/25/2010 11:44:06 AM"},{"CarID":73,"UserID":1,
"RegisteredOwner":"Balaji ","Make":"Audi","Model":"Sportz","Color":"Red","BodyType":"Coupe","PlateType":"PAS",
"PlateNumber":"SUPERMAN","State":"NJ","VINNumber":"","YearOfRegistration":2010,"ExpiryDate":"12/12/2020 12:00:00 AM",
"IsAutoFightOn":true,"IsDeleted":true,"DateAddedTimeStamp":"10/25/2010 6:36:07 PM","LastUpdatedTimeStamp":"12/9/2010 11:41:46 PM"},
{"CarID":74,"UserID":1,"RegisteredOwner":"suresh","Make":"BMW","Model":"sedane","Color":"silver","BodyType":"Convertible","PlateType":"PAS",
"PlateNumber":"GREENMAN","State":"NJ","VINNumber":"","YearOfRegistration":2010,"ExpiryDate":"12/12/2020 12:00:00 AM","IsAutoFightOn":true,"IsDeleted":false,
"DateAddedTimeStamp":"10/26/2010 10:15:34 AM","LastUpdatedTimeStamp":"12/9/2010 11:38:56 PM"},{"CarID":79,"UserID":1,"RegisteredOwner":"Balu","Make":"Hero",
"Model":"Honda","Color":"Green","BodyType":"2005","PlateType":"ARG - Air National Guard","PlateNumber":"2434","State":"NY","VINNumber":"12345",
"YearOfRegistration":2004,"ExpiryDate":"3/17/2021 12:00:00 AM","IsAutoFightOn":false,"IsDeleted":false,"DateAddedTimeStamp":"11/17/2010 9:55:32 AM",
"LastUpdatedTimeStamp":"12/6/2010 11:13:01 AM"},{"CarID":80,"UserID":1,"RegisteredOwner":"Balaji","Make":"Accura","Model":"i10","Color":"Red",
"BodyType":"1994","PlateType":"ATD - All Terrain Dealer","PlateNumber":"NOFEAR","State":"DE","VINNumber":"456789","YearOfRegistration":1999,
"ExpiryDate":"10/29/2047 12:00:00 AM","IsAutoFightOn":true,"IsDeleted":false,"DateAddedTimeStamp":"11/17/2010 11:25:54 AM",
"LastUpdatedTimeStamp":"11/17/2010 11:25:54 AM"},{"CarID":81,"UserID":1,"RegisteredOwner":"Balaji","Make":"Esteem","Model":"Honda","Color":"LemonYellow",
"BodyType":"1976","PlateType":"AYG","P
I am able to get response but it is incomplete. what am i doing wrong. I think it is because of buffer reader.

#Kishore: here's the code
String SOAP_ACTION = "service soap action";
try {
URL u = new URL("server url");
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("SOAPAction", SOAP_ACTION);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "text/xml; charset=utf-8");
String xmldata="soap request envelope";
//send the request
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
wout.write(xmldata);
wout.flush();
wout.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result;
StringBuilder builder=new StringBuilder();
//read response
while ((result=rd.readLine()) != null) {
builder.append(result);
}
thanks for your help

Related

Calling Post request without body in java

I have a post API which doesn't accept any input. I have to get output from API. But it is giving compilation error.
HttpURLConnection connection = null;
String targetUrl="https://idcs-oda-9417f93560b94eb8a2e2a4c9aac9a3ff-t0.data.digitalassistant.oci.oc-test.com/api/v1/bots/"+BotID+"/dynamicEntities/"+dynamicEntityId+"/pushRequests
URL url = new URL(targetUrl);
connection=(HttpURLConnection) url.openConnection();
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic aWRjcy1vZGEtOTQxN2Y5MzU2MGI5NGViOGEyZTJhNGM5YWFjOWEzZmYtdDBfQVBQSUQ6MjQ0YWU4ZTItNmY3MS00YWYyLWI1Y2MtOTExMDg5MGQxNDU2");
connection.setRequestProperty("Accept", "application/json");
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
**osw.write();** //this line is expecting input in parameter
osw.flush();
osw.close();
os.close();
connection.connect();
If I dont pass any value in osw.write() it gives compilation error. How can I resolve the same.
Look at the following method for the post call. You will need to add the outputstream to the osw.write() as it expects a parameter.
private static void sendPOST() throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// 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");
}
}
For more details on the above code look here.

How to send JSON data to API using HttpsURLConnection on Android?

How can I send JSON data using HttpsURLConnection to my API ?, this is my code
URL endpoint = new URL("https://api.url.com/api/token/");
// Create connection
HttpsURLConnection myConnection = (HttpsURLConnection) endpoint.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setRequestProperty("Content-Type", "application/json; utf-8");
myConnection.setRequestProperty("Accept", "application/json");
// Create the data
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
// Enable writing
myConnection.setDoOutput(true);
// Write the data
myConnection.getOutputStream().write(myData.getBytes());
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);}
}
I tried this way, but it doesn't work.
Thank you
Send the request:
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
URL url = new URL ("https://api.url.com/api/token/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try(OutputStream outputStream = conn.getOutputStream()) {
byte[] input = myData.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
To read the response:
StringBuilder sb = new StringBuilder();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
}
System.out.println(sb.toString());
I hope that helps!

Http get response utf-8

I have following code. When i get the response, it's characters are faulty. i want to get the response with "UTF-8". How and where can i write that in my code below?
Thanks
URL httpPost = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) httpPost.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.getOutputStream().write(params.getBytes(Charset.forName("UTF-8")));
connection.getOutputStream().flush();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
try {
String responseFromServer = response.toString();
dealsResponse = Utils.mapper.readValue(responseFromServer, GetDealsResponse.class);
} finally {
in.close();
}
connection.setRequestProperty("Accept-Charset", "UTF-8");

Post Request clone on Android

Im trying to perform the folowing request in my android app.
The Request i send was on a Chrome Browser.
In the Request i shortend the Form Data so there is not so much code.
Request URL:http://***/
Request Method:POST
Status Code:200 OK
Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:424
Content-Type:application/x-www-form-urlencoded
Cookie:__utma=188893489.1646114392.1358703936.1367178892.1368783485.29; __utmz=188893489.1365594840.21.3.utmcsr=***|utmccn=(referral)|utmcmd=referral|utmcct=/
Host:***
Origin:***
Referer:**
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
Form Data
date=1375480155&mail=&dfBoot=Test
Response Headers
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:3614
Content-Type:text/html
Date:Fri, 02 Aug 2013 21:49:59 GMT
Keep-Alive:timeout=15, max=100
Server:Apache/2.2.14 (Ubuntu)
Vary:Accept-Encoding
X-Powered-By:PHP/5.3.2-1ubuntu4.20
with this code:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("http://***/index.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",String.valueOf(post.length()));
//connection.setChunkedStreamingMode(0);//results in frezing
OutputStreamWriter writer = new OutputStreamWriter(
connection.getOutputStream());
writer.write(post);
writer.flush();
InputStream in = new BufferedInputStream(
connection.getInputStream());
while (in.available() != 0) {
in.read();
}
writer.close();
in.close();
} finally {
connection.disconnect();
}
The code is very messed up because i tryed manytime to fix my connection problem.
Please help with a better Solution.
Hm, I will show my working code with JSON, but maybe you can modify it.
URL url = new URL("http://xcxcxcxcxcx");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(jsonObject.toString().getBytes().length));
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(jsonObject.toString());
out.flush();
out.close();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
BufferedReader r = new BufferedReader(reader);
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
JSONObject jsonObjectResult = null;
if(typeOfMethod == 0){
JSONTokener tokenizer = new JSONTokener(total.toString());
jsonObjectResult = new JSONObject(tokenizer);
}
connection.disconnect();
return jsonObjectResult;
There is some differences between getting result from InputStream.

return StringBuffer array

I'm using StringBuffer to send and receive variables from a web service.
My code is:
// Create connection
url = new URL(urlSCS + "/login");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
"" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "pl-PL");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
How can I change this code to be able to receive Array instead of String?
The request which I get from the web service is like this: {"var", "var"}.
This might help
http://www.coderanch.com/t/393008/java/java/explode-Java
Remember to cut the response from {} using response.substring()!
look at:
String partsColl = "A,B,C";
String[] partsCollArr;
String delimiter = ",";
partsCollArr = partsColl.split(delimiter);
you will have your responses in "" so substring them then.
Good luck!

Categories