I've made a .NET service in C# that can be accessed via
http://localhost:2586/Service1.asmx/AddPackage?username=acesda&description=no%20Description&state=New&location=Home
If I use the browser, The service works fine and I can see the XML result in browser.
But, if I use the following code in a Java application, I get an HTTP 400 error:
Server returned HTTP response code: 400 for URL: http://localhost:2586/Service1.asmx/AddPackage?adminName=admin&sessionID=1388849172471&packageOwner=user&description=iPhone 4s&state=new&location=iPhone 4s
Code:
try {
String parameters = String.format(PARAMETERS_TEMPLATE, adminName, sessionID, packageOwner, description, packageState, description, location);
String url = String.format(PACKAGE_URL_TEMPLATE, "AddPackage", parameters);
Document responseDocument = Utils.getRemoteXML(url, 1000);
properties.put("success", Utils.isSuccesfull(responseDocument));
properties.put("failReason", Utils.getMessage(responseDocument));
} catch (Exception e) {
properties.put("success", "false");
properties.put("failReason", e.getMessage());
}
public static Document getRemoteXML(String url, int timeout) throws Exception {
URLConnection connection = new URL(url).openConnection();
connection.setConnectTimeout(timeout);
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(connection.getInputStream());
return document;
}
I must notice that I copied the address from exception, and it works in browser.
Thank you.
Related
I'm trying to test sending a request to Document AI using .NET framework. I didn't see any info specific to .NET on the formal Google explanations for using client libraries.
So far this is what I came up with:
public void Test()
{
var documentProcessorServiceClient = new DocumentProcessorServiceClientBuilder
{
Endpoint = "us-documentai.googleapis.com"
}.Build();
ProcessRequest request = new ProcessRequest
{
SkipHumanReview = false,
RawDocument = new RawDocument
{
MimeType = "application/pdf",
Content = ByteString.CopyFrom(bytesArray); // bytesArray of some file
}
};
try
{
ProcessResponse response = documentProcessorServiceClient.ProcessDocument(request);
Document docResponse = response.Document;
Console.WriteLine(docResponse.Text);
}
catch (Exception ex)
{
throw;
}
}
My questions are:
Why I always get the following exception:
"Error starting gRPC call. HttpRequestException: Unable to get subchannel from HttpRequestMessage."
How do I authenticate using a key instead of using OAuth2?
Thanks.
Successfully send the request with authentication.
I have a web API2 application which is consumed by a third party application. When the application hits my end-point, my application send oAuth credentials for authentication and gets the results from the third party application.
Recently some of the transactions are failing and when i added some logs, i saw that the error: The remote server returned an error: (410) Gone is occurring for all failed transactions. Unfortunately I am unable to reproduce this issue when I am calling my application. The following is the code that I am using. What could be the issue that is causing this error?
public async Task<customerModel> SendSigned(string url)
{
customerModel customermodel = null;
try
{
OAuthBase oauthBase = new OAuthBase();
string oAuthKey = ConfigurationManager.AppSettings["oAuthKey"];
string oAuthSecret = ConfigurationManager.AppSettings["oAuthSecret"];
string timestamp = oauthBase.GenerateTimeStamp();
string nonce = oauthBase.GenerateNonce();
string normalizedUrl;
string normalizedRequestParameters;
string sig = HttpUtility.UrlEncode(oauthBase.GenerateSignature(
new Uri(url), oAuthKey, oAuthSecret, string.Empty, string.Empty,
"GET", timestamp, nonce, out normalizedUrl, out normalizedRequestParameters));
string requestUrl = String.Format("{0}?{1}&oauth_signature={2}", normalizedUrl, normalizedRequestParameters, sig);
HttpWebRequest request = null;
request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
myXMLDocument = new XmlDocument();
customermodel = GetCustomerInformation(response);
}
return await Task.Run(() => customermodel);
}
catch (Exception ex)
{
_logger.Error("Error in SendSigned method", ex.InnerException);
return customermodel;
}
}
The explanation of 410 is The target resource is no longer available at the origin server and that this condition is likely to be permanent based on
this link (similar to a 404)
I would suggest you to think about recent changes you made to your
API signatures
Folder restructure/reorganization of assets/resources
Routing changes
Rename of resources
I have created a WCF Web Service using this walk through:
http://mikesknowledgebase.com/pages/Services/WebServices-Page2.htm
It returns data from a local SQL Server. The WCF Web Service takes a string parameter, and returns it back, as a string in JSON format.
I have now created a client website where i want to use the WCF Services as my data source to output the information in the database through a grid view or something similar. How do i do this? I assume i have to use some c#.
Service.cs:
public class Service : IService
{
private object cds;
public List<cdInfo> GetCDinfo()
{
try
{
CdDataClassesDataContext dc = new CdDataClassesDataContext();
List<cdInfo> results = new List<cdInfo>();
foreach (cd cD in dc.cds)
{
results.Add(new cdInfo()
{
Id = cD.Id.ToString(),
artist = cD.artist,
genre = cD.genre,
title = cD.title,
date = cD.date
});}
return results;
}
catch (Exception ex)
{
// Return any exception messages back to the Response header
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
response.StatusDescription = ex.Message.Replace("\r\n", "");
return null;}}}
Hopefully this link will help you in consuming WCF service.
https://msdn.microsoft.com/en-us/library/bb412178(v=vs.110).aspx
I have a MS Visual C# 2010 XML-RPC client app that uses the CookComputing.XmlRpc library. It works very well when it receives well-formed input. Here are the essential code elements:
using CookComputing.XmlRpc;
...
public interface IXml : IXmlRpcProxy
{
[XmlRpcMethod]
MyResponse SendRequest(MyRequest request);
}
...
// create instance of XML-RPC interface
IXml proxy = XmlRpcProxyGen.Create<IXml>();
// set URL to selected end point
proxy.Url = MyUrl;
// set the methodName
proxy.XmlRpcMethod = XmlRpcMethod;
// set request variables
MyRequest request;
string data = txtSend.Text;
request.Request = data;
// talk to server and get response
try
{
MyResponse ret = proxy.SendRequest(request);
...
}
...
catch (Exception ex)
{
txtReceive.ForeColor = Color.Red;
txtReceive.Text = ex.ToString();
}
So far, so good. However, I sometimes get a response from the server that is not valid XML-RPC. (I have no control over this.) For example:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /ngt_jrn_stg was not found on this server.</p>
</body>
</html>
When that happens, the CookComputing XML-RPC library returns an error:
CookComputing.XmlRpc.XmlRpcServerException: Not Found
at CookComputing.XmlRpc.XmlRpcClientProtocol.ReadResponse(XmlRpcRequest req, WebResponse webResp, Stream respStm, Type returnType)
at CookComputing.XmlRpc.XmlRpcClientProtocol.Invoke(Object clientObj, MethodInfo mi, Object[] parameters)
at XmlRpcProxyf2e1082a-4493-486e-9034-cea828aa54d4.SendRequest(MyRequest request)
at TestNgt.TestNgt.btnProcess_Click(Object sender, EventArgs e) in ...\Main.cs:line 328
Right now (as you can see in the code above), I catch the error and display the exception text. What I would like to know is if there is a way that I can handle this error more gracefully. Ideally, I would like to display something like "404 Not Found: The requested URL /ngt_jrn_stg was not found on this server." (from the server response HTML).
I trap the error message from XML-RPC call, but I can't find a way to programatically access the actual HTML response that caused the error. (I found the text shown above by setting up a TcpTrace instance on the port I use to communicate with the server.)
Link to XML-RPC.NET Documentation: http://xml-rpc.net/faq/xmlrpcnetfaq-2-5-0.html
Although Ksoap2 is a good library to handle SOAP messages in Android application development, it is not well documented. I've read a lot of blog posts and Q&As but information is often incomplete. Is it possible to provide a complete example of:
How to create simple web service using C#?
How to consume a webmethod on this web service on Android and parse the returned SOAP message to generate a ListView?
You can find how to create simple web service on google very easily.
I want to show you how to get data from .net web service:
first, you have to use ksoap2 library for getting data in android.
http://code.google.com/p/ksoap2-android/ download and copy into project>libs folder
second, you have to use asynctask for calling web service because you have to use asynctask for long time process in android.
If you download and copy ksoap2 library into project, lets get started.
//import ksoap2
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class Example extends Activity {
//define your web service namespace
private static final String NAMESPACE = "http://tempuri.org/";
//web service URL
private static final String URL = "http://www.example.com/webservice1.asmx";
//variables
private String username;
private String password;
private String userID;
public class ExampleAS extends AsyncTask<String,String,String>{
private ProgressDialog dialog = new ProgressDialog(Example.this);
String ParamUserName;
String ParamPassword;
public ExampleAS(String ParamUserName,String ParamPassword){
this.ParamUserName=ParamUserName;
this.ParamPassword=ParamPassword;
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
ExampleFunc(ParamUserName,ParamPassword);
return userID;
}
protected void onPostExecute(String userID){
label.setText(userID);
dialog.dismiss();
}
}
private String ExampleFunc(String ParamUserName,String ParamPassword){
PropertyInfo uName = new PropertyInfo();
uName.name= "USERNAME"; //It must be same with your webservice's parameter name
uName.setValue(ParamUserName); //Parameter value
uName.type = PropertyInfo.STRING_CLASS; //Parameter type
PropertyInfo pass = new PropertyInfo();
pass.name= "PASSWORD"; //It must be same with your webservice's parameter name
pass.setValue(ParamPassword); //Parameter value
pass.type = PropertyInfo.STRING_CLASS; //Parameter type
SoapObject request = new SoapObject(NAMESPACE, "Login"); //Namespace,Webservice method name
request.addProperty(uName);
request.addProperty(pass);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
try {
androidHttpTransport.call("http://tempuri.org/Login", envelope);
SoapObject response = (SoapObject) envelope.getResponse();
Object property = response.getProperty(0);
if(property instanceof SoapObject){
SoapObject users = (SoapObject) property;
userID = users.getProperty("user_id").toString();
}
}
catch (Exception e) {
e.printStackTrace();
}
return userID;
}
Don't copy and build it, It may not working because I write it on here. You should change some field for your request or getting data from web service.
You must call asynctask in onCreate
forexample;
new ExampleAS("admin","1234").execute();
finally, you should follow my another post :Get List from .net Web Service on Android