Can objects be appended to post requests in Java or do they have to be converted to Strings first? I know for sure they can be sent as a String using the NameValuePair class, but is there a way to send a serializable plain old Java object through a post request? How would I do that?
EDIT: I found an example, but the post request isn't going through... this is my code:
URL url = new URL("http://localhost:8080/test123/User");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true); // to be able to write.
conn.setDoInput(true); // to be able to read.
ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
out.writeObject(myObj);
out.close();
Related
Illegal Argument exception: Host name may not be null
I am getting this error at last line
HttpResponse httpResponse = httpClient.execute(get)
I tried all possible solutions like encoding url if contains space etc.. and variables like name and phone all these are from my calling class
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
String time = sdf.format(cal.getTime());
String value="Dish:"+cr.getString(1)+"Quantity:"+cr.getInt(2)+"Price"+cr.getString(3).trim()+"TotalPrice:"+Integer.parseInt(cr.getString(3))*cr.getInt(2)+"Address:"+address+"CustomerName:"+name+"RestaurantName:"+cr.getString(4).trim();
url = "http:twowaits.in/orderapp.php?name="+name.trim()+"&no="+phone.trim()+"&add="+URLEncoder.encode(address, "UTF-8")+"&rest="+URLEncoder.encode(cr.getString(4),"UTF-8")+"&cost="+cr.getString(3).trim()+"&value="+URLEncoder.encode(value, "UTF-8")+"&dishname="+cr.getString(1).trim()+"&qty="+cr.getInt(2)+"&time="+time;
HttpGet get = new HttpGet(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(get);
You forgot the // after http:.
url = "http://twowaits.in/......
The stacktrace says it all; your URL does not contain a hostname (a domain name or IP). That means you either didn't supply one, or you made a formatting error somewhere so the URL couldn't be parsed properly. In this case, you did supply a domain name, it's just that the URL isn't formatted properly.
Note that the Apache HttpClient that you are using is deprecated and Google recommends you switch to something else, e.g. URLConnection. Square's OKHttp is also a great alternative.
Also, you might want to try and make your code more readable. Using a builder pattern for your URI would probably help a lot. See URIBuilder or you could just use a StringBuilder.
I want to get Inbox via RSS, I can get XML when I use Response.Redirect , but can not get as XML format, it throws (401) unauthorized error My Code is
string url = "https://myusername:mypassword#mail.google.com/mail/feed/atom";
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();
-->Response.redirect(url); //it is working
Can any one have any idea about it,
or
is any verson of AE.Net.Mail.dll for Framework 2.0
Thanks you
The XmlReader class cannot parse authentication information from the URL, you have to create an XmlSettings instance and set its XmlResolver property to an XmlUrlResolver instance that has its credentials set to the username and password. Then when you create the XmlReader instance, you supply the custom XmlSettings instance. The following code would do the trick:
// Create a resolver with your credentials
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = new NetworkCredential("myusername", "mypassword");
// Set the reader settings object to use the resolver.
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = resolver;
string url = "https://mail.google.com/mail/feed/atom";
// Create the reader using the specified URL and settings
XmlReader reader = XmlReader.Create(url, settings);
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();
However, I tried this code and the following XmlException was thrown:
"The element with name 'feed' and namespace 'http://purl.org/atom/ns#' is not an allowed feed format."
It appears that the feeds Google outputs are in a format that is incompatible with the SyndicationFeed class. For more information see: http://www.eggheadcafe.com/tutorials/csharp/9faa101f-0a1a-465f-a41a-3e52dd9f7526/everything-rss--atom-feed-parser.aspx
I generate request to a certain API which is mentioned here for sending an sms http://help.voxeo.com/go/help/evolution.sms.postapi
The request generates an XML response as follow
<rsp stat="ok">
<success msg="accepted" transactionid="2e47fe224d25559a696a7bdddec1828b" messageid="cf0d21f067e5b386a2e042134687eb5c"/>
</rsp>
I want to read if rsp stat in response is ok or fail how can i do it .
These are the first two lines how can i get particular xml tag out of response stream
HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();
Stream content = response.GetResponseStream();
Why not use XmlDocument to parse the XML. For example,
using(var reader = new StreamReader(content))
{
var doc = new XmlDocument();
doc.LoadXml(reader.ReadToEnd());
// you may want to compare case in-sensitive
if (doc.DocumentElement.Attributes["stat"].Value == "ok")
{
// success
}
}
(There is also Load method that would load from stream directly but I am not sure if it expects xml declaration at the beginning or not)
Yet another alternative is using XmlReader in case response could be lengthy and you wants to parse the initial bits as soon as its available.
try to read with XmlTextReader (http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader%28v=vs.71%29.aspx)
I have given
[WebGet(UriTemplate = "/{year}/{issue}/{article}")]
Article GetArticle(string year, string issue, string article);
[OperationContract]
[WebInvoke(UriTemplate = "/{year}/{issue}",Method="POST")]
Article AddArticle(string year, string issue, Article article);
My URL is http://localhost:1355/Issues.svc/
if I give this I am fetching all data from the database
http://localhost:1355/Issues.svc/2010/June/A
GetArticle method fires for the filtered data to bring from db.
Similarly I have to call the Add Article(WebInvoke) method to insert data in to the database.
How should I call this method in the browser
how my url should be should I give method=post
check this post help you to achieve the task you want :Create REST service with WCF and Consume using jQuery
You won't be able to send an HTTP post from a browser by just modifying the URL. You'll have to have a web page with a HTML form, some Javascript code, some server-side code, or something else that has the ability to make an HTTP POST request to your service URL.
If you are just wanting to test your service while in development, here's a good HTTP debugging tool that you might want to check out: http://fiddler2.com
You can't use post it using browser url.
Try this code
//Creating the Web Request.
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://localhost/DemoApp/Default.aspx") as HttpWebRequest;
//Specifing the Method
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
Source : http://www.dotnetthoughts.net/2009/11/10/post-data-using-httpwebrequest-in-c-sharp/
This question is a follow up to my previous question about getting the HTML from an ASPX page. I decided to try using the webclient object, but the problem is that I get the login page's HTML because login is required. I tried "logging in" using the webclient object:
WebClient ww = new WebClient();
ww.DownloadString("Login.aspx?UserName=&Password=");
string html = ww.DownloadString("Internal.aspx");
But I still get the login page all the time. I know that the username info is not stored in a cookie. I must be doing something wrong or leaving out an important part. Does anyone know what it could be?
Try setting the credentials property of the WebClient object
WebClient ww = new WebClient();
ww.Credentials = CredentialCache.DefaultCredentials;
ww.DownloadString("Login.aspx?UserName=&Password=");
string html = ww.DownloadString("Internal.aspx");
Just pass valid login parameters to a given URI. Should help you out.
If you don't have login information you shouldn't be trying to circumvent it.
public static string HttpPost( string URI, string Parameters )
{
System.Net.WebRequest req = System.Net.WebRequest.Create( URI );
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes( Parameters );
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write( bytes, 0, bytes.Length );
os.Close();
System.Net.WebResponse resp = req.GetResponse();
if ( resp == null ) return null;
System.IO.StreamReader sr = new System.IO.StreamReader( resp.GetResponseStream() );
return sr.ReadToEnd().Trim();
}
Well does opening the page in a brower with "Login.aspx?UserName=&Password=" normaly work?
Some pages may not allow login using data provided in the url, and that it must be entered in the login form on the page and then submitted.
The only other reason I can think of then is that the web page is intentionally blocking it from loggin in. If you have access to the code, take a look at the loggin system used to see if theres anything designed to block such logins.
Use Fiddler to see the HTTP requests and responses that happen when you do it manually through the browser.
#Fire Lancer: I asked myself that same question during my tests, so I checked, and it does work from a browser.
As the aspx page I was trying to get was in my own projct, I could use the Server.Execute method. More details in my answer to my original question
Use Firefox with the LiveHttpHeaders plugin.
This will allow you to login via an actual browser and see EXACTLY what is being sent to the server. My first question would be to verify that it isn't expecting a POST from the form. The example URL you are loading is sending the info via a querystring GET.