Access Internet with requestcorresponding model

zhaozj2021-02-16  54

Request / corresponding model

Mainly 3 classes: URI, WebRequest, WerResponse.

And Internet communication processes:

1): Create

WebRequest

WebRequest WREQ = WebRequest.create ("

http://www.contoso.com/ ");

2)

Set any required attribute values ​​in WebRequest. For example, if you want to support authentication, please

Credentials

Attribute settings

Networkcredential

Instance of class

Wreq.credentials =

New NetworkCredential (UserName, SecureLyStoredPassword);

To access

HttpWebRequest

HTTP-specific properties, please

WebRequest conversion is

HttpWebRequest (otherwise processed).

3): Download resources from Internet, call

WebRequest

GetResponse

method. transfer

WebRequest

GetRequestStream

Method, and use results

Stream

Object written data,

WebResponse WRESP = WREQ.GETRESPONSE ();

4): GetResponseSstream method Gets streams that contain response data from network resources.

Stream Respstream = WRESP.GETRESPONSESTREAM ();

StreamReader Reader = New StreamReader (RESPSTREAM, Encoding.ASCII);

String resphtml = reader.readToend ();

Console.writeline (Resphtml);

RESPSTREAM.CLOSE (); // Don't forget this step.

Httpwebrequest.contentType

Get or set

The value of the Content-Type HTTP header.

HttpWebRequest.Method property

Get or set up a request

You can set the Method property to any HTTP 1.1 protocol predicate: GET, HEAD, POST, PUT, DELETE, TRACE, or OPTIONS.

If the ContentLength property is set to -1, you must set the Method property to the protocol properties of upload data.

HttpWebRequest.contentLength attribute

The number of bytes to be sent to the Internet resource. The default is -1, which indicates that this property has not been set and the request data to be sent.

The ContentLength property contains the Content-Length HTTP header value to be sent as a request.

In addition to any value other than -1, the ContentLength property indicates that the upload data is allowed to set upload data only in the Method property.

Once the ContentLength property is set to a value, the number of bytes must be written to the request stream returned by calling getRequestStream or simultaneously calling BegingerEtRequestStream and EndgetRequestStream.

string postData = "firstone =" inputData; ASCIIEncoding encoding = new ASCIIEncoding (); byte [] byte1 = encoding.GetBytes (postData); // Set the content type of the data being posted.myHttpWebRequest.ContentType = "application / x -www-form-urlencoded "; // Set the content length of the string being posted.myHttpWebRequest.ContentLength = postData.Length; Stream newStream = myHttpWebRequest.GetRequestStream (); newStream.Write (byte1,0, byte1.Length); Console.writeline ("The value of 'contentLength' Property After Sending The Data IS {0}", MyHttpWebRequest.contentLength; newstream.close ();

转载请注明原文地址:https://www.9cbs.com/read-20875.html

New Post(0)