简体   繁体   中英

Android equivalent of WebClient in .NET

I have a fairly basic application that I wrote in C# NET some time ago and would like to rewrite it for the Android platform. It just uses an API exposed by some web software, and I can access it with just a WebClient in .NET.

WebClient myClient = new WebClient();

//Prepare a Name/Value Collection to hold the post values
NameValueCollection form = new NameValueCollection();
form.Add("username", "bob");
form.Add("password", GetMD5Hash("mypass"));
form.Add("action", "getusers");

// POST data and read response
Byte[] responseData = myClient.UploadValues("https://mysite.com/api.php", form);
string strResponse = Encoding.ASCII.GetString(responseData);

I found the WebKit ( android.webkit | Android Developers) but just from quick looking that doesn't seem appropriate.

Does anyone have any sample code of how to port this over?

This could be an equivalent:

List<NameValuePair> form = new ArrayList<NameValuePair>();
form.add(new BasicNameValuePair("username", "bob");
// etc...

// Post data to the server
HttpPost httppost = new HttpPost("https://mysite.com/api.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httppost);

To summarize HttpClient could replace your WebClient. Then you have to use either HttpPost for posting data or HttpGet for retrieving data. There are some tutorials that you can read to help you understand how you could use these classes like this one .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM