Home  >  Article  >  Java  >  Detailed explanation of using HttpURLConnection to send data instances in java

Detailed explanation of using HttpURLConnection to send data instances in java

怪我咯
怪我咯Original
2017-06-30 10:41:242018browse

This article mainly introduces the relevant information about a simple example of using HttpURLConnection to send data in java. Friends who need it can refer to it

java A simple example of using HttpURLConnection to send data

Each HttpURLConnection instance can be used to generate a single request, but other instances can transparently share the underlying network connection to the HTTP server. Calling the close() method on an HttpURLConnection's InputStream or OutputStream after a request releases the network resources associated with this instance but has no effect on the shared persistent connection. If the persistent connection is idle when disconnect() is called, the underlying socket may be closed. JAVA uses HttpURLConnection to send POST data in the form of OutputStream flow

Implementation code:

import java.io.*;
import java.net.*;

public class PostExample {
  public static void main(String[] argv) throws Exception {
     URL url = new URL("http://www.javacourses.com/cgi-bin/names.cgi");
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     connection.setRequestMethod("POST");
     connection.setDoOutput(true);
     PrintWriter out = new PrintWriter(connection.getOutputStream());
    // encode the message
     String name = "name="+URLEncoder.encode("Qusay Mahmoud", "UTF-8");
     String email = "email="+URLEncoder.encode("qmahmoud@javacourses.com", "UTF-8");
    // send the encoded message
     out.println(name+"&"+email);
     out.close();
     BufferedReader in
       = new BufferedReader(new InputStreamReader(connection.getInputStream()));
     String line;
    while ((line = in.readLine()) != null) {
       System.out.println(line);
     }
     in.close();
   }
}

The above is the detailed content of Detailed explanation of using HttpURLConnection to send data instances in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn