Pack API response (java)

Introduction

Recently, it was troublesome to copy and paste the result in the API test and mark it with 〇, so I made it a little ...

This time, I write the URL in a txt file, just call it, pack it in a list, and write it to a file. It feels like you're just moving, so I think it's a lot of waste, but please close your eyes: frowning2:

If you create an apitest folder directly under C, put a txt file in it and execute it, you should get the execution result ...

txt file

apiTest.txt


//The one who calls the postal code of Hyogo prefecture
https://zip-cloud.appspot.com/api/search?zipcode=6580083
https://zip-cloud.appspot.com/api/search?zipcode=6580026
https://zip-cloud.appspot.com/api/search?zipcode=6580025
https://zip-cloud.appspot.com/api/search?zipcode=6580082
https://zip-cloud.appspot.com/api/search?zipcode=6580024

Source code

ApiTest.java


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ApiTest {
	public static void main(String[] args) throws InterruptedException {
			//Path to the folder containing the API execution URL
			final String filePath = "C:\\apitest\\";

			//apiURL Files already prepared
			List<String> apiUrl = new ArrayList<>();

			//Stores API results.
			List<String> apiResult = new ArrayList<>();


			//File path for local
	 		File file = new File(filePath);

			try {
				if (file.isDirectory()) {
					String[] fileList = file.list();
					//Read all the files in the folder for the time being so that you can do various things in the future with the file name str
					for(String str:fileList) {
						try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + str)))) {
							//A one-line string-> line
							String line;
							while ((line = reader.readLine()) != null) {
								apiUrl.add(line);
							}
						}
					}
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
			for(int i=0;i < apiUrl.size();i++) {
				if(apiUrl.get(i) == null) {
				//When there is no execution URL
					apiResult.add("");
				}else {
					apiResult.add(callGet(apiUrl.get(i)));
				}
			}
			//Export the result to a text file
			try(FileWriter fileWrite = new FileWriter("C:\\apitest\\apiResult.txt");
					PrintWriter pw = new PrintWriter(new BufferedWriter(fileWrite));) {
					//Export to file
				for(int i=0 ;i<apiResult.size();i++) {
					pw.println(apiResult.get(i));
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}



		public static String callGet(String strGetUrl){

			HttpURLConnection con = null;
			StringBuffer result = new StringBuffer();

			try {

				URL url = new URL(strGetUrl);

				con = (HttpURLConnection) url.openConnection();
				//Basic authentication pattern
				//con.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString("userName:pass".getBytes()));

				con.setRequestMethod("GET");
				con.connect();

				//HTTP response code
				final int status = con.getResponseCode();
				if (status == HttpURLConnection.HTTP_OK) {
					//Successful communication
					//Get the text
					final InputStream in = con.getInputStream();
					String encoding = con.getContentEncoding();
					if(null == encoding){
						encoding = "UTF-8";
					}
					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);
					}
					bufReader.close();
					inReader.close();
					in.close();
				}else{
					System.out.println(status);
				}

			}catch (Exception e1) {
				e1.printStackTrace();
			} finally {
				if (con != null) {
					//Disconnect
					con.disconnect();
				}
			}
			System.out.println("result=" + result.toString());

			return result.toString();
		}

	}

Finally

In some cases, there is basic authentication, so I also described the pattern. If you get a 401 error, you usually have Basic authentication, so if you write the Basic authentication part, I feel like you can do something about it.

That's it: relaxed:

reference

http://www.programing-style.com/android/android-api/android-httpurlconnection-get-text/

Recommended Posts

Pack API response (java)
Java Stream API
[Java] Stream API / map
Docker-Client Java API Troubleshooting
Java8 Stream API practice
Zabbix API in Java
Java Stream API cheat sheet
Java Stream API in 5 minutes
[Java] Stream API --Stream termination processing
[Java] Stream API --Stream intermediate processing
[Java] Introduction to Stream API
Java Basic Learning Content 8 (Java API)
[Java] Stream API intermediate operation
Recent Java API specification generation
[Java] "T" is included in date type JSON in API response
[java8] To understand the Stream API
Export issues using JIRA's Java API
[Introduction to Java] About Stream API
Java HTTP Client API timeout setting
Generate CloudStack API URL in Java
Java
Hit Zaim's API (OAuth 1.0) in Java
I tried using Java8 Stream API
Parsing the COTOHA API in Java
Java
Call TensorFlow Java API from Scala
Java 8 ~ Stream API ~ to start now
JPA (Java Persistence API) in Eclipse
Implement API Gateway Lambda Authorizer in Java Lambda
Data processing using stream API from Java 8
Studying Java 8 (date API in java.time package)
Call GitHub API from Java Socket API part2
API integration from Java with Jersey Client
Try using the Stream API in Java
Call the Windows Notification API in Java
Nowadays Java lambda expressions and Stream API
[MarkLogic] CRUD + α by "Java Client API"
Hit the Salesforce REST API from Java
Try using JSON format API in Java
Try various Java Stream API methods (now)
Java 8 to start now ~ Date time API ~
The Java EE Security API is here!
When calling API with java, javax.net.ssl.SSLHandshakeException occurs
[Java] New Yahoo! Product Search API Implementation