In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "introduction of two ways to connect Http in Java". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the introduction of two ways to connect Http in Java.
There are two ways to connect http in java, one is java's HttpUrlConnection, the other is apacha's httpClient, the latter is a third-party class library that needs to be imported from the outside. At the same time, this is the first time to use an external class library, and there will be many requirements to import external class libraries in the future. Http protocol is a protocol based on tcp. Tcp is a reliable transmission protocol, which ensures the transmission of data through three-way handshake and loss retransmission.
First let's take a look at HttpUrlConnection.
This class is included with java, so just import it. The process of using tcp connection is almost the same, there are two ways in http protocol, one is get, the other is post submission, some web pages need to submit data, so use.
Take a look at GET first.
First you need a url, which is set up using String
String path = ""; / / URL url = new URL (path)
Then open the connection through the url object
HttpURLConnection conn = (HttpURLConnection) url.openConnection ()
Here, it is important to note that after opening the connection, this function returns a httpUrlconnection type but a URLConnection type, which can be forced directly. Then start setting the parameters of the connection by setting the conn object
Conn.setRequestMethod ("GET"); / / sets the method of this request. The default is GET, and the parameter requirements are all uppercase conn.setConnectTimeout (5000); / / set connection timeout conn.setDoInput (true); / / whether to open the input stream, this method defaults to true conn.setDoOutput (true); / / whether to open the output stream, this method defaults to false conn.connect (); / / indicates the connection
After that, we start to determine whether the connection is successful, and the server will return a response code, probably our 404, but there are many more, and the successful connection returns 200, and there is also a static name instead of HTTP_OK.
You can use an if to judge: int code = conn.getResponseCode ()
When we are sure that the connection is successful, we need to open the server's output stream and read data from this stream
InputStream is = conn.getInputStream (); String name = path.substring (path.lastIndexOf ("/") + 1); System.out.println ("name =" + name); fos = new FileOutputStream ("C:\\ pro\" + name); byte [] buffer = new byte [1024]; int len = 0; while ((len = is.read (buffer))! =-1) {fos.write (buffer, 0, len)
Here you get the stream through getinputStream, and then write the file to disk c through the FileOutputStream stream. This is the end of the download file.
Here's post.
Compared with get, it is set to POST when setting the request method, and then submit the data to be submitted.
OutputStream os = conn.getOutputStream (); os.write ("platform=2&appVersion=1.7.0&osType=2" .getBytes ()); os.flush ()
The output stream of the server is obtained, and the data is written, separated by &. Other than that, it's exactly the same.
HttpClient
First of all, we need to import a third-party class library. The first part is definitely the need to download HttpClient's jar package.
Get three jar packages like this, then create a new libs folder in the project, and copy the three jar packages into it.
Select these three packages, then right-click Bulid Path, and after importing the package, you can use the HttpClient class. First of all, you still need a url.
String path = ""
Then create a HttpClient object
HttpClient client = new DefaultHttpClient ()
Then create a GET request object
HttpGet httpGet = new HttpGet (path)
Then connect through the execute function of Client
HttpResponse response = client.execute (httpGet)
The parameter is the get request object, and what is returned is a httpresponse object, which is the result we got, and then we do the same for the response operation, let's first judge the response code
Response.getStatusLine () .getStatusCode () = 200
Here we first get the status line, and then we get the status code inside. We can get an entity HttpEntity through this Response.
HttpEntity entity = response.getEntity ()
From this entity we can get a stream using getContent () as above, but this class provides us with a simpler method. There are toByteArray (entity) and toString (entity) methods in the EntityUtils class, which return byte [] and string, respectively. For the byte array, we can use FileOutputStream to write to the file stream.
Post mode
It's the same as above, except for a few more operation parts.
HttpPost httpPost = new HttpPost (path); / / create a container to submit data List parames = new ArrayList (); parames.add (new BasicNameValuePair ("platform", "2")); parames.add (new BasicNameValuePair ("appVersion", "1.7.0")); parames.add (new BasicNameValuePair ("osType", "2")); / / encapsulate the container into request parameters HttpEntity entity = new UrlEncodedFormEntity (parames); / / set request parameters to httpPost.setEntity (entity) in post request / / execute post request HttpResponse response = client.execute (httpPost)
The type here becomes HttpPost, then add the parameters of post to the container, then pass the container to an entity, send the request to post, and then execute.
At this point, I believe you have a deeper understanding of the "introduction of two ways to connect Http in Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.