Soapheader cannot be serialized - c#

well I am trying to develop a soap client, it wanted its custom soapheader(i.e.usercred) to serialized, but after doing so I get this as error
System.Runtime.Serialization.InvalidDataContractException: 'Type 'ConsoleApp1.Program+usercred' cannot inherit from a type that is not marked with DataContractAttribute or SerializableAttribute. Consider marking the base type System.Web.Services.Protocols.SoapHeader with DataContractAttribute or SerializableAttribute, or removing them from the derived type.'
it kinda wants soapheader to be also serialized plz help

There are several ways to add custom soup header in your soup request.
For example you can create soup request using HTTPRequest where you can build soup envelope as you want. Client to send SOAP request and receive response
public override string Process(string UserName,string Password)
{
string uri = "https://serviceURL";
HttpWebRequest req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(uri));
req.ContentType = "application/soap+xml; charset=utf-8";
req.Method = "POST";
string soapRequest = BuildSoapRequest(UserName,Password);
StreamWriter stm = new StreamWriter(req.GetRequestStream(), Encoding.UTF8);
stm.Write(soapRequest);
stm.Close();
try
{
HttpWebResponse wr = (HttpWebResponse)req.GetResponse();
StreamReader srd = new StreamReader(wr.GetResponseStream());
string response = srd.ReadToEnd();
return ExtractResponse(response);
}
catch (WebException e)
{
string error = "";
HttpWebResponse errRsp = (HttpWebResponse)e.Response;
if (errRsp != null)
{
using (StreamReader rdr = new StreamReader(errRsp.GetResponseStream()))
{
string line;
while ((line = rdr.ReadLine()) != null)
{
error += line;
}
}
}
throw new Exception(e.Message + "<br/> " + error);
}
catch (Exception e)
{
throw e;
}
}
private string BuildSoapRequest(string UserName,string Password)
{
StringBuilder soapRequest = new StringBuilder();
soapRequest.Append("<soap:Envelope xmlns:cor=\"http://www.caqh.org/SOAP/WSDL/CORERule2.2.0.xsd\" xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\">");
soapRequest.Append("<soap:Header>");
soapRequest.Append("<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">");
soapRequest.Append("<wsse:UsernameToken>");
soapRequest.Append("<wsse:Username>" + UserName + "</wsse:Username>");
soapRequest.Append("<wsse:Password>" + Password + "</wsse:Password>");
soapRequest.Append("</wsse:UsernameToken>");
soapRequest.Append("</wsse:Security>");
soapRequest.Append("</soap:Header>");
soapRequest.Append("<soap:Body>");
soapRequest.Append("</soap:Body>");
soapRequest.Append("</soap:Envelope>");
return soapRequest.ToString();
}
private static string ExtractResponse(string soap)
{
}
If you are consuming WCF service then you can add custom behavior in your request.
Custom Endpoint Behavior not being used in WCF Client with Service Reference
public class CustomClientBehavior : IEndpointBehavior
{
string _username;
string _password;
public CustomClientBehavior(string username, string password)
{
_username = username;
_password = password;
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
CustomInspector inspector = new CustomInspector(_username, _password);
clientRuntime.MessageInspectors.Add(inspector);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
public class CustomClientBehaviorExtensionElement : BehaviorExtensionElement
{
string _username;
string _password;
public CustomClientBehaviorExtensionElement(string username, string password)
{
_username = username;
_password = password;
}
public override Type BehaviorType
{
get { return typeof(CustomClientBehavior); }
}
protected override object CreateBehavior()
{
return new CustomClientBehavior(_username, _password);
}
}
public class CustomInspector : IClientMessageInspector
{
string _username;
string _password;
public CustomInspector(string username, string password)
{
_username = username;
_password = password;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
return;
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
request.Headers.Clear();
string headerText = "<wsse:UsernameToken xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
"<wsse:Username>{0}</wsse:Username>" +
"<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">" +
"{1}</wsse:Password>" +
"</wsse:UsernameToken>";
headerText = string.Format(headerText, _username, _password);
XmlDocument MyDoc = new XmlDocument();
MyDoc.LoadXml(headerText);
XmlElement myElement = MyDoc.DocumentElement;
System.ServiceModel.Channels.MessageHeader myHeader = MessageHeader.CreateHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", myElement, false);
request.Headers.Add(myHeader);
return Convert.DBNull;
}
}
Test Client should be like
TestService.Client objClient = new TestService.Client();
objClient.Endpoint.Behaviors.Add(new CustomClientBehavior(UserName, Password));
You can also try WebService Headers Authentication

Related

ReasonPhrase is always empty

The rest API server is under "Spring boot", the client is under XAMARIN FORM and I use HttpClient to get or post data to the server.
Is there a specific format that must be sent by a rest API in case of an error to fill, in HttpClient, the ReasonPhrase? Because the ReasonPhrase is always empty even on error.
the format I send from the rest API is normally a standard like this :
{
"timestamp": "2022-09-11T17:58:02.811+00:00",
"status": 404,
"error": "Not Found",
"message": "No message available",
}
In the example, the reasonPhrase should have "No message available"
SPRING BOOT code
My Exception Handler code:
#ControllerAdvice
public class AppExceptionsHandler extends ResponseEntityExceptionHandler {
// Handle a specific error
#ExceptionHandler(value = { ApplicationException.class })
public ResponseEntity<Object> handleUserServiceException(ApplicationException ex, WebRequest request) {
ErrorMessage errorMessage = new ErrorMessage(new Date(), HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
// Handle unknown error
#ExceptionHandler(value = { Exception.class })
public ResponseEntity<Object> handleOtherExceptions(Exception ex, WebRequest request) {
ErrorMessage errorMessage = new ErrorMessage(new Date(), ex.getMessage());
return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
My Exception code:
public class ApplicationException extends RuntimeException{
private static final long serialVersionUID = 7289264700624277238L;
public ApplicationException(String message)
{
super(message);
}
}
My error message object code:
public class ErrorMessage {
private Date timestamp;
private HttpStatus status;
private String message;
public ErrorMessage() {}
public ErrorMessage(Date timestamp, HttpStatus status, String message)
{
this();
this.timestamp = timestamp;
this.message = message;
this.status = status;
}
*** some more code getter and setter ***
}
When I throw the exception in the code:
*** some code ***
throw new ApplicationException("Wrong user");
Xamarin code
internal class HttpMethods
{
private HttpClient _httpClient;
public HttpMethods()
{
_httpClient = new HttpClient();
_httpClient.Timeout = TimeSpan.FromSeconds(15);
_httpClient.MaxResponseContentBufferSize = 256000;
_httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
}
public async Task<(TA, ErrorDto)> HttpPost<TA, TB>(string url, string token, TB data)
{
var result = default(TA);
var error = new ErrorDto();
HttpResponseMessage response = new();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpContent content;
content = FileContent(data as string);
response = await _httpClient.PostAsync(new Uri(url), content);
if (response.IsSuccessStatusCode)
{
var jsonDataResponse = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<TA>(jsonDataResponse);
}
else
{
error.ReasonPhrase = (int)response.StatusCode;
error.StatusCode = (string)response.ReasonPhrase;
}
return (result, error);
}
}
Thanks for your help
PS: Edited for code details.

How to add ws-security header in .net core?

I'm trying to make a call to a webservice and want to manually add the ws-security headers into the request because .net core 2.2 currently does not support ws-security.
I have created my custom security header class:
public class SoapSecurityHeader : MessageHeader
{
private readonly string _password, _username;
public SoapSecurityHeader(string id, string username, string password)
{
_password = password;
_username = username;
}
public override bool MustUnderstand => true;
public override string Name
{
get { return "Security"; }
}
public override string Namespace
{
get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
}
protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteStartElement("wsse", Name, Namespace);
writer.WriteAttributeString("s", "mustUnderstand", "http://schemas.xmlsoap.org/soap/envelope/", "1");
writer.WriteXmlnsAttribute("wsse", Namespace);
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteStartElement("wsse", "UsernameToken", Namespace);
writer.WriteAttributeString("wsu", "Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "UsernameToken-32");
// Username
writer.WriteStartElement("wsse", "Username", Namespace);
writer.WriteValue(_username);
writer.WriteEndElement();
// Password
writer.WriteStartElement("wsse", "Password", Namespace);
writer.WriteAttributeString("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
writer.WriteValue(_password);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
And this is my method calling the SOAP service:
public ActionResult<Ted_Result> Get(DateTime dateFrom, DateTime dateTo, int? pageFrom, int? pageTo)
{
BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
EndpointAddress endpointAddress = new EndpointAddress(new Uri("https://localhost/SomeService.svc"));
ChannelFactory<IConnectPublicService> factory = new ChannelFactory<IConnectPublicService>(basicHttpBinding, endpointAddress);
GetContractNoticesResponseMessage result = null;
// Bypass SSL/TLS secure channel validation
#if DEBUG
factory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication
{
CertificateValidationMode = X509CertificateValidationMode.None,
RevocationMode = X509RevocationMode.NoCheck
};
#endif
// Debugging inspector
factory.Endpoint.EndpointBehaviors.Add(new InspectorBehavior());
IConnectPublicService serviceProxy = factory.CreateChannel();
((ICommunicationObject)serviceProxy).Open();
var opContext = new OperationContext((IClientChannel)serviceProxy);
var soapSecurityHeader = new SoapSecurityHeader("UsernameToken-32", "sampleUsername", "samplePassword123");
// Adding the security header
opContext.OutgoingMessageHeaders.Add(soapSecurityHeader);
var prevOpContext = OperationContext.Current; // Optional if there's no way this might already be set
OperationContext.Current = opContext;
var info = new ExternalIntegrationRequestMessageInfo
{
UserCode = "1000249",
CompanyCode = "200000040"
};
var request = new GetContractNoticesRequestMessage
{
Info = info,
DateFrom = dateFrom,
DateTo = dateTo,
PageFrom = pageFrom,
PageTo = pageTo
};
result = serviceProxy.GetContractNoticesAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();
return Ok(result);
}
If I put a breakpoint inside the inspector at BeforeSendRequest I can see that the security header is added to the request:
<wsse:Security s:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-32" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>sampleUsername</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">samplePassword123</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
And putting a breakpoint inside the inspector at AfterReceiveReply, I get the CORRECT result, but I still get an exception.
The result:
<...>
<s:Header>
<...>
<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<u:Timestamp u:Id="_0">
<u:Created>2019-01-11T19:42:53.606Z</u:Created>
<u:Expires>2019-01-11T19:47:53.606Z</u:Expires>
</u:Timestamp>
</o:Security>
</s:Header>
<s:Body>
<GetContractNoticesResponseMessage>
<ContractNotices>....</ContractNotices>
</GetContractNoticesResponseMessage>
</s:Body>
The exception:
An unhandled exception occurred while processing the request.
ProtocolException: The header 'Security' from the namespace 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' was not understood by the recipient of this message, causing the message to not be processed. This error typically indicates that the sender of this message has enabled a communication protocol that the receiver cannot process. Please ensure that the configuration of the client's binding is consistent with the service's binding.
Why do I still get an exception after calling the webservice successfully?
For .net core 2.2 you need to pass Security header manually. You'll need to-do some workarounds - WCF isn't fully implemented yet in .Net Core (has been stated by project contributors). Assuming the requirements aren't too complex, you should be able to get something going without too much headache.
public class SecurityHeader : MessageHeader
{
public UsernameToken UsernameToken { get; set; }
public override string Name => "Security";
public override string Namespace => "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
public override bool MustUnderstand => true;
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
XmlSerializer serializer = new XmlSerializer(typeof(UsernameToken));
serializer.Serialize(writer, this.UsernameToken);
}
}
[XmlRoot(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")]
public class UsernameToken
{
[XmlAttribute(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")]
public string Id { get; set; }
[XmlElement]
public string Username { get; set; }
}
Add below code in BeforeSendRequest method
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
var soapSecurityHeader = new SecurityHeader()
{
UsernameToken = new UsernameToken()
{
Username = "User Name"
}
};
request.Headers.Add(soapSecurityHeader);
}
I did some digging and in the AfterReceiveReply you could do this:
public void AfterReceiveReply(ref Message reply, object correlationState)
{
var security = reply.Headers.Where(w => w.Namespace == "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd").First();
reply.Headers.UnderstoodHeaders.Add(security);
}
I suppose that in this step you could also check the value of the timestamp, if DateTime.UtcNow is in range and act upon that...?

Using Created HttpWebResponse Interface Returns 401 Unauthorized Error

So I originally had this code for the web request:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.UseDefaultCredentials = true;
WebResponse response = request.GetResponse();
which I changed to this in order to add unit tests:
IHttpWebRequest request = IHttpWebRequestFactory.Create(uri);
request.UseDefaultCredentials = true;
IWebResponse response = request.GetResponse();
IHttpWebRequest:
public interface IHttpWebRequest
{
bool UseDefaultCredentials { get; set; }
IWebResponse GetResponse();
}
MyHttpWebRequest:
public class MyHttpWebRequest : IHttpWebRequest
{
private readonly HttpWebRequest httpWebRequest;
private bool useDefaultCredentials;
public MyHttpWebRequest(HttpWebRequest httpWebRequest)
{
this.httpWebRequest = httpWebRequest;
}
public bool UseDefaultCredentials
{
get { return useDefaultCredentials; }
set { useDefaultCredentials = value; }
}
public IWebResponse GetResponse()
{
return new MyWebResponse((HttpWebResponse)httpWebRequest.GetResponse());
}
}
IHttpWebRequestFactory:
public interface IHttpWebRequestFactory
{
IHttpWebRequest Create(string Uri);
}
HttpWebRequestFactory:
public class HttpWebRequestFactory : IHttpWebRequestFactory
{
public IHttpWebRequest Create(string Uri)
{
return new MyHttpWebRequest((HttpWebRequest)WebRequest.Create(Uri));
}
}
IWebResponse:
public interface IWebResponse
{
Stream GetResponseStream();
}
MyWebResponse:
public class MyWebResponse : IWebResponse
{
private WebResponse webResponse;
public MyWebResponse(HttpWebResponse webResponse)
{
this.webResponse = webResponse;
}
public Stream GetResponseStream()
{
return webResponse.GetResponseStream();
}
}
But the website now returns a HTTP Error 401 Unauthorized. Using Fiddler works though. I also tried setting request.Credentials = CredentialCache.DefaultNetworkCredentials, request.PreAuthenticate = true, etc. but to no avail. :(
I also tried supplying my username and password to Credentials but the unauthorized error still appears, which is odd since the original code above works. :(
You are not using useDefaultCredentials correctly, try this:
MyHttpWebRequest:
public class MyHttpWebRequest : IHttpWebRequest
{
private readonly HttpWebRequest httpWebRequest;
public MyHttpWebRequest(HttpWebRequest httpWebRequest)
{
this.httpWebRequest = httpWebRequest;
}
public bool UseDefaultCredentials
{
get { return this.httpWebRequest.UseDefaultCredentials; }
set { this.httpWebRequest.UseDefaultCredentials = value; }
}
public IWebResponse GetResponse()
{
return new MyWebResponse((HttpWebResponse)httpWebRequest.GetResponse());
}
}

Web request to .NET Web Api Service gets 401 unauthorized error

I have a web api service that I want another .Net app to make a web request to, however I'm getting the following error when doing so:
"The remote server returned an error: (401) Unauthorized."
Just to clarify, these are 2 separate .net apps that are trying to communicate.
Here's the code for the client .Net c# app trying to make the web request to the other web api service:
public string MakeWebRequest()
{
var requestUrl = "http://localhost:8081/api/Tests/results";
var request = WebRequest.Create(requestUrl);
var username = "test";
var password = "test";
SetBasicAuthHeader(request, username, password);
var postData = "thing1=hello";
postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
//request.Expect = "application/json";
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
return null;
}
public static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
And here's the code of the .Net c# web api service that should receive the web request from the other app:
[RoutePrefix("api/Tests")]
public class TestsApiController : ApiController
{
[POST("results")]
[AcceptVerbs("POST")]
[HttpPost]
[BasicAuthAuthorize(Roles="Admin")]
public JObject resultsFinished()
{
//do something
}
}
And here's the Basic Auth Attribute I created, which doesn't even get hit from the client service.
public class BasicAuthAuthorizeAttribute : AuthorizeAttribute
{
private const string BasicAuthResponseHeader = "WWW-Authenticate";
private const string BasicAuthResponseHeaderValue = "Basic";
public override void OnAuthorization(HttpActionContext actionContext)
{
try
{
AuthenticationHeaderValue authValue = actionContext.Request.Headers.Authorization;
if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter) && authValue.Scheme == BasicAuthResponseHeaderValue)
{
var parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);
if (parsedCredentials != null)
{
if (parsedCredentials.Username == IoC.Username && parsedCredentials.Password == IoC.Password)
return;
}
}
}
catch (Exception)
{
//actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
actionContext.Response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);
return;
}
}
private Credentials ParseAuthorizationHeader(string authHeader)
{
string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[] { ':' });
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]))
return null;
return new Credentials() { Username = credentials[0], Password = credentials[1], };
}
}
//Client credential
public class Credentials
{
public string Username { get; set; }
public string Password { get; set; }
}
Try using a tool like fiddler to troubleshoot what is being sent to the web service:
http://www.telerik.com/fiddler

Android to ASP.NET error processing the request

When I send a request from Android to ASP.NET method there is an error:
W/DefaultRequestDirector﹕ Authentication error: Unable to respond to any of these challenges: {}
W/MainActivity﹕ Error 401 for URL
I/jsonResultStr :﹕ {"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}
This is the ASP.NET method prototype:
public string GetBuildingData(string roadId)
This is the Android sendToAsp method:
public void sendToAsp() {
HttpPost httpPost = new HttpPost("http://madenati.alameentech.com:8082/Coding/Services/BuildingsServices.asmx/GetBuildingData");
httpPost.setHeader("content-type", "application/json");
HttpClient httpClient = new DefaultHttpClient(getHttpParameterObj(4000,4000));
JSONObject data = new JSONObject();
try {
data.put("roadId", "1");
StringEntity entity = new StringEntity(data.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonResultStr = reader.readLine();
data = new JSONObject(jsonResultStr);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " );
}
Log.i("jsonResultStr : ",jsonResultStr);
} catch(Exception e) {
Log.v("Exception","Exception sendToAsp");
}
}
This is getHttpParameterObj method:
private HttpParams getHttpParameterObj(int timeOutConnection,int timeOutSocket)
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeOutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeOutSocket);
return httpParameters;
}
and in Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
What could be the problem?
Use this class to do request:
package com.alameen.mat;
import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class WebService extends AsyncTask<String, String, String>
{
public String NameSpace = "";
public String MethodName = "";
SoapObject request;
SoapSerializationEnvelope envelope;
HttpTransportSE androidHttpTransport;
String URL="";
Activity context;
public WebService(Activity c, String nameSpace, String method, String url)
{
context=c;
NameSpace=nameSpace;
MethodName=method;
request = new SoapObject(NameSpace, MethodName);
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
URL=url;
androidHttpTransport = new HttpTransportSE(URL,30000);
}
public void addProperty(String name,String val)
{
request.addProperty(name,val);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Log.i("jsonArray from ASP.NET: ",result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try
{
androidHttpTransport.call(params[0], envelope);
SoapObject result = (SoapObject)envelope.bodyIn;
String res = result.getProperty(0).toString();
//Log.d("result", res);
return res;
}
catch(Exception e)
{
SoapFault fault = (SoapFault)envelope.bodyIn;
Log.d("error", fault.getMessage()+"/"+fault.getCause());
e.printStackTrace();
}
return null;
}
void log(String l)
{
Log.d("status", l);
}
}
call like this:
public static String URL="http://... .asmx?WSDL";
WebService ws = new WebService(This, "http://tempuri.org/", "methodName", URL);
and import this library to your project:
https://www.dropbox.com/s/j5bi6yt8x5xpdbk/ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar?dl=0

Categories

Resources