I have a webservice with one function checkOrder(String, String, String) return String.
How do I call a function checkOrder from Controller.
My code:
WSRequest ws = WS.url("https://www.nganluong.vn/public_api.php?wsdl/");
ws.parameters.put("merchant_id", merchant_site_code);
ws.parameters.put("param", payment_id);
ws.parameters.put("checksum", checksum);
WS.HttpResponse rs = ws.post();
Related
I m new to Mockito and trying to mock the webservice responses, I did tried mocking at some extent few Objects got worked, But the end mocked WebResponse is always returning null.
Service Method i am going to test:getWebResponse Method
public WebResponse getWebResponse(String crmNumber) throws JSONException, ExecutionException, WebException {
Map<String, String> HEADERS_POST = new HashMap<String, String>() {
{
put(WebUtil.HEADER_CONTENT, WebUtil.CONTENT_JSON);
put(WebUtil.HEADER_ACCEPT, WebUtil.CONTENT_JSON);
}
};
JSONObject requestJson = new JSONObject();
requestJson.put("crmNumber", crmNumber);
requestJson.put("application", "ABCD");
requestJson.put("feature", "DDDFL");
// Using internal web service becuase device authentication is done separately.
String url = CommonUtil.getServiceBaseUrl(true) + "/ett";
WebServiceClient client = WebServiceClientRegistry.getClient(ApacheCustom.class);
WebRequest webReq = new GenericWebRequest(WebRequestMethod.POST, url, HEADERS_POST, requestJson.toString());
// Till here i m getting all mocked object (client also Mocked) after this stament the webRes is returning null;
WebResponse webRes = client.doRequest(webReq);
return webRes;
}
And here the test Method:
#Test
public void getWebResponseTest() {
mockStatic(CommonUtil.class);
mockStatic(WebServiceClientRegistry.class);
this.webResponse = new GenericWebResponse(200, "", new HashMap(), "");
try {
Mockito.when(CommonUtil.getServiceBaseUrl(true)).thenReturn("https://stage.com/service");
WebRequest webReq = new GenericWebRequest(WebRequestMethod.POST, "https://stage.com/service", new HashMap(), "");
Mockito.when(WebServiceClientRegistry.getClient(ApacheCustom.class)).thenReturn(client);
Mockito.when(client.doRequest(webReq)).thenReturn(this.webResponse);
WebResponse wesponse = this.ServiceResponse.getWebResponse("Number");
Assert.assertEquals(wesponse.getStatusCode(), 200);
} catch (Exception e) {
Assert.fail();
}
}
But the getWebResonse method from Test class always returning null Response(Even Though it is mocked)
You mock client.doRequest as follows:
Mockito.when(client.doRequest(webReq)).thenReturn(this.webResponse);
but you create a new instance of WebRequest in your service under test.
You call doRequest with a different argument than recorded in your test.
Arguments are compared with equals.
Most likely WebRequest does not override equals, so recorded interaction is ignored and a default response (null) is rerurned.
I guess WebResuest may not be the code you own (you haven’t specified this in your question), so it may be impossible to override it.
Thus, you can use a different argument matcher.
You can use ArgumentMatchers.any() for good start, or implement a custom argument matcher.
I'm trying to upload a byte array to a remote WS with multipart/form-data in play! framework using Scala. My code is:
//create byte array from file
val myFile = new File(pathName)
val in = new FileInputStream(myFile)
val myByteArray = new Array[Byte](audioFile.length.toInt)
in.read(audioByteArray)
in.close()
// create parts
val langPart = new StringPart("lang", "pt")
val taskPart = new StringPart("task","echo")
val audioPart = new ByteArrayPart("sbytes", "myFilename", myByteArray, "default/binary", "UTF-8")
val client: AsyncHttpClient = WS.client
val request = client.preparePost(RemoteWS)
.addHeader("Content-Type", "multipart/form-data")
.addBodyPart(audioPart)
.addBodyPart(taskPart)
.addBodyPart(langPart).build()
val result = Promise[Response]()
// execute request
client.executeRequest(request, new AsyncCompletionHandler[AHCResponse]{
override def onCompleted(response: AHCResponse): AHCResponse = {
result.success(Response(response))
response
}
override def onThrowable(t: Throwable) {
result.failure(t)
}
})
// handle async response
result.future.map(result =>{
Logger.debug("response: " + result.getAHCResponse.getResponseBody("UTF-8"))
})
Every time I execute this request, it throws this exception:
java.io.IOException: Unable to write on channel java.nio.channels.SocketChannel
The remote server is OK, I can make sucessfull requests using for example Postman.
I'm using Play Framework:
play 2.2.3 built with Scala 2.10.3 (running Java 1.8.0_05)
Version of AsyncHttpClient:
com.ning:async-http-client:1.7.18
Any help is welcome!
I am attempting to bind to a web service at run time and call a simple method to get this code working, and get the above error message when I try to get the reply from the web service. Below is the following code, first how I'm invoking the service:
Public Sub BeginInvoke(invokeCompleted As AsyncCallback)
Dim invoke As New DelegateInvokeService(AddressOf Me.InvokeWebService)
Dim result As IAsyncResult = invoke.BeginInvoke(invokeCompleted, Nothing)
End Sub
Public Function EndInvoke(result As IAsyncResult) As String
Dim asyncResult = DirectCast(result, AsyncResult)
Dim message As ReturnMessage = DirectCast(asyncResult.GetReplyMessage(), ReturnMessage)
Return message.ReturnValue.ToString()
End Function
Public Function InvokeWebService() As String
Try
'Create the request
Dim request As HttpWebRequest = CreateWebRequest()
'write the soap envelope to request stream
Using s As Stream = request.GetRequestStream()
Using writer As New StreamWriter(s)
writer.Write(CreateSoapEnvelope())
End Using
End Using
'get the response from the web service
Dim response As WebResponse = request.GetResponse()
Dim stream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(stream)
Dim str = reader.ReadToEnd()
Return StripResponse(HttpUtility.HtmlDecode(str))
Catch ex As Exception
Return ex.Message
End Try
End Function
Now for building the soap package and web request:
Private Function CreateSoapEnvelope() As String
Dim method As String = "<" & WebMethod & " xmlns=""http://tempuri.org/"">"
Dim params As String = Parameters.Aggregate(String.Empty, Function(current, param) current & "<" & param.Name & ">" & param.Value & "</" & param.Name & ">")
method &= params & "</" & WebMethod & ">"
Dim sb As New StringBuilder(SoapEnvelope)
sb.Insert(sb.ToString().IndexOf("</soap:Body>"), method)
Return sb.ToString()
End Function
Private Function CreateWebRequest() As HttpWebRequest
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(Url), HttpWebRequest)
If WSServiceType = ServiceType.WCF Then
request.Headers.Add("SOAPAction", """http://tempuri.org/" & WCFContractName & "/" & WebMethod & """")
Else
request.Headers.Add("SOAPAction", """http://tempuri.org/" & WebMethod & """")
End If
request.Headers.Add("To", Url)
request.ContentType = "text/xml;charset=""utf-8"""
request.Accept = "text/xml"
request.Method = "POST"
Return request
End Function
The SoapEnvelope variable looks like so:
Private Const SoapEnvelope As String = "<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></soap:Body></soap:Envelope>"
And this is how I'm calling the above invoking:
Protected Sub GoButtonClick(sender As Object, e As EventArgs) Handles GoButton.Click
_oClient = New SoapClient()
Dim params As New List(Of SoapClient.Parameter)
params.Add(New SoapClient.Parameter() With {.Name = "str", .Value = "Richard"})
With _oClient
.Url = "http://localhost:7659/WebServices/SampleService.asmx"
.WebMethod = "HelloWorld"
.WSServiceType = SoapClient.ServiceType.Traditional
.Parameters = params
End With
_oClient.BeginInvoke(AddressOf InvokeCompleted)
End Sub
Public Sub InvokeCompleted(result As IAsyncResult)
ErrorMessage.Text = _oClient.EndInvoke(result)
End Sub
The error is generated on this line in InvokeWebService
'get the response from the web service
Dim response As WebResponse = request.GetResponse()
Anyone know where I'm going wrong here?
It turned out to be a problem with my sample web service I was testing with, once I fixed that error the above code works beautifully.
while make a webservice call out I am getting below error:
Web service callout failed: Unexpected element. Parser was expecting element 'http://schemas.xmlsoap.org/soap/envelope/:Envelope' but found ':HTML'
Please see below code which I am trying for this:
public class TestUtility_Cls{
public list<Test_webService.KeyValuePair> IOG_pair = new list<Test_webService.KeyValuePair>();
public pageReference calltestServices(){
I_pair = new list<Test_webService.KeyValuePair>();
Test_webService.webPort bindobj = new Test_Iwebervice.RtPort();
bindobj.clientCertName_x = 'xxxxxxxxxxxxxx';
bindobj.timeout_x = 120000;
bindobj.inputHttpHeaders_x = new Map<String, String>();
bindobj.inputHttpHeaders_x.put('Authorization', 'xxxxxxxxx');
Test_webService.KeyValuePair I_KeyValue = new Test_webService.KeyValuePair();
I_KeyValue.key = 'SessionId';
I_KeyValue.value = 'Carrie09';
I_pair.add(I_KeyValue);
I_KeyValue = new Test_webService.KeyValuePair();
I_KeyValue.key = 'CR';
I_KeyValue.value = 'ExOffer';
I_pair.add(I_KeyValue);
Test_webService.ArrayOfKeyValuePair kevapair = new Test_webService.ArrayOfKeyValuePair();
kevapair.attribute = I_pair;
Test_webService.ProcessEventResponse_element IResp = new Test_webService.ProcessEventResponse_element();
IResp = bindingobj.ProcessEvent('QA', 'GetOffers', kevapair);
return null;
}
}
Here I am using WSDL generated class's method.
Can someone help on this. How to resolve it?
Thanks,
public pageReference calltestServices(){
I think above method refers a html page reference from which you are extracting your input data.You are forming your input request in html format while your webservice is expectng soap envelope. I think you need to wrap or convet or edit your request, formed in above method as soap envelope, then only your server accept it.
I would like to call .Net webservice from my Blackbrry application. How can I call webservice from my app and which protocol is user and which jar file i have to used to call webservice. and how to get responce from webservice in Blackberry?
you can use something like this (you probably need to setup correct request headers and cookies):
connection = (HttpConnection) Connector.open(url
+ ConnectionUtils.getConnectionString(), Connector.READ_WRITE);
connection.setRequestProperty("ajax","true");
connection.setRequestProperty("Cookie", "JSESSIONID=" + jsessionId);
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + responseCode);
}
responseString = rawResponse.toString();