Summary of Java communication API (2) How to use HttpUrlConnection

1. 1. Introduction

This time I will briefly summarize how to use HttpUrlConnection. HttpURLconnection is to support requests such as get, post, put, delete based on http. Usually the get and post methods are often used. Therefore, this article also explains the get and post methods.

2. How to use the GET method

First, specify getUrl and use getUrl as a parameter to create an instance of the URL class. Tried to make it. Once you get the connection target, start communication, return the response code, and if successful, the input stream Read the data information with.

String getUrl = "https://github.com/Hyman1993";
URL url = new URL(getUrl);
//instance of connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//Specify request method
connection.setRequestMethod("GET");
//Start communication
connection.connect();
//Return response code
int responseCode = connection.getResponseCode();
//Judge the response code, if OK, proceed
if(responseCode == HttpURLConnection.HTTP_OK){
      //Successful communication
      //Get the text
      InputStream in= connection.getInputStream();
      String encoding = con.getContentEncoding();
      if(null == encoding){
          encoding = "UTF-8";
      }
  StringBuffer result = new StringBuffer();
  final InputStreamReader inReader = new InputStreamReader(in, encoding);
  final BufferedReader bufReader = new BufferedReader(inReader);
  String line = null;
  //Read text line by line
  while((line = bufReader.readLine()) != null) {
      result.append(line);
  }
  //Close
  bufReader.close();
  inReader.close();
  in.close();
  //Output
  Log.log("result=============:"+result);
}

Also, when passing parameters, you can define the url as follows.

String getUrl = "https://github.com/Hyman1993?userName=Hyman1993&password=123456";

3. 3. How to use the POST method

Regarding the POST method, the most important thing is to get the output stream from the connection and write the data information to the server. Next, let's explain with an example.

3.1 Upload JSON data

Please refer to the source below.

            String postUrl = "https://github.com/Hyman1993";
            URL url = new URL(postUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //Designated for POST
            connection.setRequestMethod("POST");
            //Output possible
            connection.setDoOutput(true);
            //Can be entered
            connection.setDoInput(true);
            //No cache
            connection.setUseCaches(false);
      //Specify the data type as json
      connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //Connection, communication start
            connection.connect();
            //Write json data to output stream
       String body = "userName=hyman1993&password=123456";
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(body);
            writer.close();

            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                      //Successful communication
		      //GET method as well
            }

3.2 Upload file

    String postUrl = "https://github.com/Hyman1993";
    URL url = new URL(postUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setRequestProperty("Content-Type", "file/*");
    connection.connect();

    OutputStream outputStream = connection.getOutputStream();
    FileInputStream fileInputStream = new FileInputStream("file");
    int length = -1;
    byte[] bytes = new byte[1024];
    while ((length = fileInputStream.read(bytes)) != -1){
        outputStream.write(bytes,0,length);
    }
    fileInputStream.close();
    outputStream.close();

    int responseCode = connection.getResponseCode();
    if(responseCode == HttpURLConnection.HTTP_OK){
                 //Successful communication
                 //GET method as well
    }

Finally

Thank you for reading to the end. This time, I plan to summarize how to use SocketChannel.

Recommended Posts

Summary of Java communication API (2) How to use HttpUrlConnection
Summary of Java communication API (1) How to use Socket
[Java] [Maven3] Summary of how to use Maven3
[java] Summary of how to handle char
[java] Summary of how to handle character strings
How to use Java API with lambda expression
[Java] How to use Map
How to use Chain API
[Java] How to use Map
How to use java Optional
How to use java class
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to use string.format
How to use Java Map
How to use Java variables
[Java] How to use Optional ①
[Java] How to use compareTo method of Date class
Summary of how to implement default arguments in Java
How to use Java HttpClient (Get)
How to use Java HttpClient (Post)
[Java] How to use join method
How to use setDefaultCloseOperation () of JFrame
[Processing × Java] How to use variables
[JavaFX] [Java8] How to use GridPane
How to use class methods [Java]
[Java] How to use List [ArrayList]
How to use classes in Java?
[Processing × Java] How to use arrays
How to use Java lambda expressions
[Java] How to use Math class
How to use Java enum type
How to use trained model of tensorflow2.0 with Kotlin / Java
How to use JSON data in WebSocket communication (Java, JavaScript)
[Must-see for apprentice java engineer] How to use Stream API
How to call and use API in Java (Spring Boot)
Summary of how to use the proxy set in IE when connecting with Java
How to make a Java calendar Summary
Multilingual Locale in Java How to use Locale
[Java] How to use the File class
[Java] How to use the hasNext function
How to use submit method (Java Silver)
[Java] How to use the HashMap class
Summary of how to write annotation arguments
[Easy-to-understand explanation! ] How to use Java instance
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
How to use Java classes, definitions, import
[Easy-to-understand explanation! ] How to use Java polymorphism
[Processing × Java] How to use the class
How to use Java Scanner class (Note)
[Ruby on Rails] "|| =" ← Summary of how to use this assignment operator
[Processing × Java] How to use the function
[Easy-to-understand explanation! ] How to use ArrayList [Java]
[Java] How to use the Calendar class
[Java] Learn how to use Optional correctly
[Easy-to-understand explanation! ] How to use Java overload
try-catch-finally exception handling How to use java
[Easy-to-understand explanation! ] How to use Java encapsulation
[Java] How to use substring to cut out a part of a character string
[Java] Note how to use RecyclerView and implementation of animated swipe processing.