How to process Data table in android>My service return dataTable.How to handle it?
public static final String APPURL = "http://192.168.1.213:6969/MySalesServices";
private static final String METHOD_NAME = "SalesList";
private static final String NAMESPACE = "http://tempuri.org/";
private static String SOAP_ACTION = "http://tempuri.org/IMySalesServices/SalesList";
SoapPrimitive responsePrimitive = null;
ArrayList<String> tablesName = new ArrayList<String>();
public void onCreate(Bundle savedInstanceState) {
..................
}
public SoapPrimitive soapPrimitive(String METHOD_NAME, String SOAP_ACTION,String NAMESPACE, String URL) throws IOException, XmlPullParserException {
SoapPrimitive responses = null;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); // set up
request.addProperty("strExec", strExecutive);
request.addProperty("strBusinessUnit", strBusinessUnit);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // put all required data into a soap
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport httpTransport = new AndroidHttpTransport(URL);
httpTransport.debug = true;
try {
httpTransport.call(SOAP_ACTION, envelope);
responses = (SoapPrimitive) envelope.getResponse();
}catch(SocketException ex){
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return responses;
}
I got following error :
AnyType{element=anyType{complexType=anyType{choice=anyType{element=anyType{complexType=anyType{sequence=anyType{element=anyType{}; element=anyType{}; element=anyType{}; element=anyType{}; element=anyType{}; }; }; }; }; }; }; }
please help me
You return the Method type as String & concert it Datatable to Json as String that is good way to do & easy
//Converting table to json
public String ConverTableToJson(DataTable dtDownloadJson)
{
string[] StrDc = new string[dtDownloadJson.Columns.Count];
string HeadStr = string.Empty;
if (dtDownloadJson.Rows.Count > 0)
{
for (int i = 0; i < dtDownloadJson.Columns.Count; i++)
{
StrDc[i] = dtDownloadJson.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
if (HeadStr.Length > 0)
{
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dtDownloadJson.TableName + "\" : [");
for (int i = 0; i < dtDownloadJson.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dtDownloadJson.Columns.Count; j++)
{
TempStr = TempStr.Replace(dtDownloadJson.Columns[j] + j.ToString() + "¾", dtDownloadJson.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}else
{
return "0";
}
}
else
{
return "0";
}
}
The error you are getting aint an error at all. At least, thats the behavious I saw at my own application using a setup that was quite like the one you have there. Have you tried casting the response to a SoapObject? You can then call the .getPropertyCount() method on that SoapObject to start looping trough the content of the response. Quick example:
//Create a Transport object makes the webservice call
HttpTransportSE httpTrans = new HttpTransportSE(URL);
httpTrans.call(SOAP_ACTION, env);
//Cast the object to SoapObject
SoapObject storages = (SoapObject)env.getResponse();
//Loop trough the result
for(int i = 0; i < storages.getPropertyCount(); i++) {
//Get a SoapObject for each storage
SoapObject storage = (SoapObject)storages.getProperty(i);
}
Seeing the response you got, you might have to dig a few levels deep to get the data you need tho. Either 6 or 7 levels deep. If it is an option, I would change the response you get from the webservice so that it is easier to parse.
Related
On Android, I get the following error when I try to md5 a string:
"Performing stop of activity that is not resumed"
I need to attach the md5 to a URL.
Please help
//md5 code
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(text.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
}
//request code
encryptedTaskId = MDConversion.MD5(taskId);
Log.v("inside doInBackground :: ", "inside doInBackground :: ");
totalUrl = baseUrl + "&access_token=" + accessToken + "&id=" + encryptedTaskId;
Log.v("fetch users to forward task url :: ", "url :: "+totalUrl);
HttpGet get = new HttpGet(totalUrl);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
response = client.execute(get);
Try to use this static function:
public static final String md5(final String toEncrypt) {
try {
final MessageDigest digest = MessageDigest.getInstance("md5");
digest.update(toEncrypt.getBytes());
final byte[] bytes = digest.digest();
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(String.format("%02X", bytes[i]));
}
return sb.toString().toLowerCase();
} catch (Exception exc) {
return ""; // Impossibru!
}
}
My webservice;
[WebMethod]
public int insertNhanVien(string[] arr)
{
SqlConnection con = new SqlConnection();
// con.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=Bai1;Integrated Security=True";
con.ConnectionString = "server=.\\SQLEXPRESS;database=QLNV;uid=sa;pwd=123456";
con.Open();
int n = 0;
for (int i = 0; i < arr.Length; i++)
{
string[] s = arr[i].ToString().Split(',');
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert Into MUser(Ten,Tuoi) values(" + s[0].Replace("'", "''") + "," + s[1] + ")";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
n = cmd.ExecuteNonQuery();
}
return n;
}
And code in android:
private boolean insertNhanVient() {
boolean result = false;
try {
String NAMESPACE ="http://tempuri.org/";
String METHOD_NAME ="insertNhanVien";
String URL ="http://localhost:10829/WebSite/Service.asmx";
String SOAP_ACTIONS = NAMESPACE + "/" + METHOD_NAME;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String [] arr =new String[3];
arr[0]="le,12";
arr[1]="hoang,33";
arr[2]="nhung,23";
request.addProperty("arr", arr);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidhttpTranport = new HttpTransportSE(URL);
try {
androidhttpTranport.call(SOAP_ACTIONS, envelope);
} catch (IOException e3) {
result = false;
} catch (XmlPullParserException e3) {
result = false;
}
Object responseBody = null;
try {
responseBody = envelope.getResponse();
String t = responseBody.toString();
if (t.equals("1")) {
result = true;
}
} catch (SoapFault e2) {
result = false;
}
} catch (Exception e) {
result = false;
} finally {
}
return result;
}
Why show exception: java.lang.RuntimeException: Cannot serialize: [Ljava.lang.String;#4051d0a0 ?
you can't pass whole array.. so you have to use seprator ## in String ..and pass it service... and change on service respectivley.
String commasepratedString="";
for(int i=0;i<arr.length();i++)
{
if(i!=(arr.length-1))
{
commasepratedString=commasepratedString+arr[i]+"##";
}
else
{
commasepratedString=commasepratedString+arr[i];
}
}
request.addProperty("arr", commasepratedString);
and change service code like this way
[WebMethod]
public int insertNhanVien(string commasepratedString)
{
String arr[] = commasepratedString.Split('##');
SqlConnection con = new SqlConnection();
// con.ConnectionString = "Data Source=.\\SQLEXPRESS;InitialCatalog=Bai1; Integrated Security=True";
con.ConnectionString = "server=.\\SQLEXPRESS;database=QLNV;uid=sa;pwd=123456";
con.Open();
int n = 0;
for (int i = 0; i < arr.Length; i++)
{
string[] s = arr[i].ToString().Split(',');
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert Into MUser(Ten,Tuoi) values(" + s[0].Replace("'", "''") + "," + s[1] + ")";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
n = cmd.ExecuteNonQuery();
}
return n;
}
replace this line
request.addProperty("arr", arr);
with this
request.addProperty("arr", arr[0]);
you cannot pass whole array.you should pass one element of it.
Update
You can add multiple properties like
request.addProperty("prop1", arr[0]);
request.addProperty("prop2", arr[1]);
request.addProperty("prop3", arr[2]);
I am consuming a web service by soap method from Android. And I am showing the values from that web service in to two separate text views on the next screen.
Here that web service is returning two values. But I'm only able to show one value from that web service in text view on the next screen.
But I need to show both values in two separate textview boxes on the next screen....
How can I do this?
Suggestions please..
NOTE :- The input value for that web service is for FromDate : 01/01/2012 and
for ToDate : 07/07/2012
Please find my sources for reference
Main_WB.java
public class Main_WB extends Activity
{
EditText edt1,edt2;
//TextView txt_1;
Button btn;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edt1 = (EditText)findViewById(R.id.editText1);
edt2 = (EditText)findViewById(R.id.editText2);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
getTMSChart(edt1.getText().toString(),edt2.getText().toString());
Intent myint = new Intent(Main_WB.this,ResultActivity.class);
startActivity(myint);
}
});
}
private void getTMSChart(String FromDate,String ToDate)
{
// txt_1 = (TextView)findViewById(R.id.textView1);
System.setProperty("http.keepAlive", "false");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
String NAMESPACE = "http://tempuri.org/";
String URL = "http://54.251.60.177/TMSOrdersService/TMSDetails.asmx";
String METHOD = "GetTMSChart";
SoapObject request = new SoapObject(NAMESPACE, METHOD);
request.addProperty("FromDate", FromDate);
request.addProperty("ToDate", ToDate);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try
{
androidHttpTransport.call(NAMESPACE + METHOD, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
SoapObject root = (SoapObject) ((SoapObject)(result).getProperty(0)).getProperty("NewDataSet");
int tablesCount = root.getPropertyCount();
for (int i = 0; i < tablesCount; i++)
{
SoapObject table = (SoapObject) root.getProperty(i);
int propertyCount = table.getPropertyCount();
// String[] ord = new String[propertyCount];
// String[] fre = new String[propertyCount];
// int[] fre = new int[propertyCount];
// int[] margin = new int[propertyCount];
for (int j = 0; j < propertyCount; j++)
{
String x,y;
// int orderNo = Integer.parseInt(table.getPropertyAsString("Order_No"));
// int freightRate = Integer.parseInt(table.getPropertyAsString("Freight_Rate"));
// int marginPercent = Integer.parseInt(table.getPropertyAsString("Margin_Percent"));
String orderNo = table.getPropertyAsString("Order_No");
String freight = table.getAttributeAsString("Freight_Rate");
x = orderNo.toString();
y = freight.toString();
Intent in = new Intent(getApplicationContext(),ResultActivity.class);
in.putExtra("gotonextpageX",x);
in.putExtra("gotonextpageY", y);
startActivity(in);
//ord[j] = orderNo;
// fre[j] = freightRate;
// margin[j]= marginPercent;
// x = orderNo.toString();
// y = fre.toString();
// Intent myIntent = new Intent(Main_WB.this, ResultActivity.class);
// myIntent.putExtra("gotonextpage", x);
// startActivity(myIntent);
// whatever you do with these values
}
}
}
catch (Exception e)
{
}
} }
ResultActivity.java
public class ResultActivity extends Activity
{
String x,y;
TextView txt1,txt2;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
x = extras.getString("gotonextpageX");
y = extras.getString("gotonextpageY");
}
else
{
}
txt1 = (TextView)findViewById(R.id.txtVw);
txt2 = (TextView)findViewById(R.id.txtVw2);
txt1.setText(x);
txt2.setText(y);
}}
Thanks for your precious time!..
Here check it out ...
public class Main_WB extends Activity {
EditText edt1, edt2;
// TextView txt_1;
Button btn;
ArrayList<String> result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edt1 = (EditText) findViewById(R.id.editText1);
edt2 = (EditText) findViewById(R.id.editText2);
btn = (Button) findViewById(R.id.button1);
result = new ArrayList<String>();
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
result.addAll(getTMSChart(edt1.getText().toString(), edt2.getText().toString()));
Intent in = new Intent(getApplicationContext(), ResultActivity.class);
in.putExtra("gotonextpageX", result.get(0));
in.putExtra("gotonextpageY", result.get(1));
startActivity(in);
}
});
}
private ArrayList<String> getTMSChart(String FromDate, String ToDate) {
// txt_1 = (TextView)findViewById(R.id.textView1);
System.setProperty("http.keepAlive", "false");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
String NAMESPACE = "http://tempuri.org/";
String URL = "http://54.251.60.177/TMSOrdersService/TMSDetails.asmx";
String METHOD = "GetTMSChart";
SoapObject request = new SoapObject(NAMESPACE, METHOD);
request.addProperty("FromDate", FromDate);
request.addProperty("ToDate", ToDate);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
String x = "", y = "";
ArrayList<String> stringResult = new ArrayList<String>();
try {
androidHttpTransport.call(NAMESPACE + METHOD, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
SoapObject root = (SoapObject) ((SoapObject) (result).getProperty(0)).getProperty("NewDataSet");
int tablesCount = root.getPropertyCount();
for (int i = 0; i < tablesCount; i++) {
SoapObject table = (SoapObject) root.getProperty(i);
int propertyCount = table.getPropertyCount();
for (int j = 0; j < propertyCount; j++) {
stringResult.add(table.getPropertyAsString("Order_No").toString());
stringResult.add(table.getPropertyAsString("Freight_Rate").toString());
}
}
} catch (Exception e) {
}
return stringResult;
}
}
And dont change your second class, this must work.
In my case, I have a soap response which has an "ArrayOfArrayOfString" type of values stored in it.
It is like an Array A[4][4].
A[0][0] -> ServiceId
A[0][1] -> ServiceName
A[0][2] -> ServiceImageURL
A[0][3] -> ServiceDecription
A[0][4] -> ServiceIconURL
and its all same upto A[4][4].
How can I handle this type of response in android?
Code is something like:
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transportSE = new HttpTransportSE(URL);
transportSE.debug = true;
Log.i("WebService", "msg:try_out");
String[] columns = null;
ArrayList<String> rows = new ArrayList<String>();
try
{
Log.i("WebService", "msg:try+in");
transportSE.call(SOAP_ACTION, envelope);
Log.i("WebService", "msg:SoapObject");
SoapObject response = (SoapObject)envelope.getResponse();
Log.i("WebService", "Response");
try
{
// WhaT SHOULD I USE HERE to convert it to 2D Array//
}
catch (Exception e)
{
e.printStackTrace();
Log.v("CATCH BLOCK", e.getMessage());
}
}
catch (Exception e)
{
e.printStackTrace();
Log.i("WebService", "msg:Exception error");
Log.i("WebSerivce", e.getMessage());
return e.getMessage();
}
Please help me regarding this.
This is the perfect working code to parse the complex data...
I am only doing this for A[0][1-4] and according to my soap response modify the code according to ur soap response.
SoapObject result = (SoapObject)enevlop.getResponse();
String str = result.getProperty(0).toString();
// add a for loop for ur code and iterate it according to ur soap response and get all the node using getProperty(i);
String str1 = lameParser(str);
textView.setText(""+str1);
Now define lameParser() method:-
public String lameParser(String input){
String sName=input.substring(input.indexOf("sName=")+6, input.indexOf(";", input.indexOf("sName=")));
int IGoals=Integer.valueOf(input.substring(input.indexOf("iGoals=")+7, input.indexOf(";", input.indexOf("iGoals="))));
String sCountry=input.substring(input.indexOf("sCountry=")+9, input.indexOf(";", input.indexOf("sCountry=")));
String sFlag=input.substring(input.indexOf("sFlag=")+6, input.indexOf(";", input.indexOf("sFlag=")));
return sName+"\n"+Integer.toString(IGoals)+"\n"+sCountry+"\n"+sFlag;
}
Here's code to parse multiple child node of xml data...
public static void parseBusinessObject(String input, Object output) throws NumberFormatException, IllegalArgumentException, IllegalAccessException, InstantiationException{
Class theClass = output.getClass();
Field[] fields = theClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Type type=fields[i].getType();
fields[i].setAccessible(true);
//detect String
if (fields[i].getType().equals(String.class)) {
String tag = "s" + fields[i].getName() + "="; //"s" is for String in the above soap response example + field name for example Name = "sName"
if(input.contains(tag)){
String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag)));
if(strValue.length()!=0){
fields[i].set(output, strValue);
}
}
}
//detect int or Integer
if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
String tag = "i" + fields[i].getName() + "="; //"i" is for Integer or int in the above soap response example+ field name for example Goals = "iGoals"
if(input.contains(tag)){
String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag)));
if(strValue.length()!=0){
fields[i].setInt(output, Integer.valueOf(strValue));
}
}
}
//detect float or Float
if (type.equals(Float.TYPE) || type.equals(Float.class)) {
String tag = "f" + fields[i].getName() + "=";
if(input.contains(tag)){
String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag)));
if(strValue.length()!=0){
fields[i].setFloat(output, Float.valueOf(strValue));
}
}
}
}
}
If you will like the post give me the up vote so that visitors find it easily....
try
{
Log.i("WebService", "Try Block");
transportSE.call(SOAP_ACTION, envelope);
Log.i("WebService", "msg:SoapObject");
SoapObject response = (SoapObject)envelope.getResponse();
Log.i("WebService", "Response on");
int totalService = response.getPropertyCount();
int i;
String str ;
String str1;
for (i = 0; i < totalService; i++)
{
str = response.getProperty(i).toString();
Log.i("WebService", "ForLoop "+ Integer.toString(i));
str1 = lameParser(str, i);
Log.i("WebService", "ForLoop: lameParser done");
Log.i("WebService", "Value Stored:: "+ str1);
}
}
catch (Exception e)
{
e.printStackTrace();
Log.i("WebService", "msg:Exception error");
Log.i("WebSerivce", e.getMessage());
}
}
private String lameParser(String input, int I)
{
int i = I;
Log.i("WebService", "LameParse()" );
try
{
String SId = input.substring(input.indexOf("{string=")+8, input.indexOf(";", input.indexOf("{string=")));
String SName = input.substring(input.indexOf(" string=")+8, input.indexOf(";", input.indexOf(" string=")));
String SIurl = input.substring(input.indexOf("http"), input.indexOf(";", input.indexOf("http")));
String SIcon = input.substring(input.indexOf("jpg; string=")+12, input.indexOf("; }", input.indexOf("jpg; string=")));
// String[][] arr = new String[x][y]; is already initialized as local var of class.
arr[i][0] = SId;
arr[i][1] = SName;
arr[i][2] = SIurl;
arr[i][3] = SIcon;
return SId + "\n" + SName + "\n" + SIurl + "\n" + SIcon + "\n" ;
}
catch (Exception e)
{
Log.i("WebService", "catch exception" );
Log.i("WebService", e.getMessage());
return null;
}
}
Here's how I processed ArrayOfArrayOfString objects.
SoapObject result = (SoapObject)envelope.bodyIn;
if (result.getPropertyCount() > 0) {
SoapObject Rows = (SoapObject)result.getProperty(0);
int nRows = Rows.getPropertyCount();
for (int nRow=0; nRow<nRows; nRow++) {
SoapObject Cols = (SoapObject)Rows.getProperty(nRow);
int nCols = Cols.getPropertyCount();
for (int nCol=0; nCol<nCols; nCol++) {
String sCol = Cols.getProperty(nCol).toString();
// Process sCol with nRow and nCol as array indexes
}
}
}
I have developed a WCF Service .NET4 (SOAP) and I am trying to upload files from Android.
With .NET client work fine, but with Android wont work, below code I am using in Android.
the the WCF service recive the data, the stream seems to be empty (zero length).
Please help me.
public class WCFclient {
private static final String METHOD_NAME = "UploadFile";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://192.168.1.103/AndroidWCF/Service1.svc";
private static final String SOAP_ACTION = "http://tempuri.org/ITransferService/UploadFile";
public static String extractText(byte[] _data)
{
#SuppressWarnings("unused")
int lun = _data.length;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
MarshalBase64 marshal = new MarshalBase64();
PropertyInfo p1=new PropertyInfo();
p1.setName("request");
p1.setType(_data);
request.addProperty(p1);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
envelope.setOutputSoapObject(request);
marshal.register(envelope);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, 20000);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SoapObject result = null;
try {
result = (SoapObject)envelope.getResponse();
} catch (SoapFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String resultData=result.getProperty(0).toString();
return resultData;
}
// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
}
The error happened in the WCF service, exception is: "Start element 'request' from namespace 'http://tempuri.org/' expected. Found element 'image' from namespace 'http://tempuri.org/'. Line 1, position 304."
Public Sub UploadFile(request As Stream) Implements ITransferService.UploadFile
Dim writeStream As FileStream = New FileStream("c:\" & Now.Ticks.ToString & ".bmp", FileMode.Create, FileAccess.Write)
ReadWriteStream(request, writeStream)
End Sub
Private Sub ReadWriteStream(readStream As Stream, writeStream As Stream)
Dim Length As Integer = 256
Dim buffer As [Byte]() = New [Byte](Length - 1) {}
Dim bytesRead As Integer = readStream.Read(buffer, 0, Length)
' write the required bytes
While bytesRead > 0
writeStream.Write(buffer, 0, bytesRead)
bytesRead = readStream.Read(buffer, 0, Length)
End While
readStream.Close()
writeStream.Close()
End Sub
You should add "" to SOAP_ACTION
private static final String SOAP_ACTION = "\"http://tempuri.org/ITransferService/UploadFile\"";
This question has been asked many a times .
From my experience this error comes when METHOD_NAME , NameSpace, URI , Soap_Action is incorrect.