Socket
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I'm thinking on the premise of a smartphone!
//If you are connected to the internet, I will try to connect to the site asynchronously!
//First, check the connection!
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
Network network = manager.getActiveNetwork();
NetworkCapabilities capabilities = manager.getNetworkCapabilities(network);
//Check your net connection with hasTransport in capabilities
// Wi-If you are connected by either Fi or mobile communication, Socket communication will be performed asynchronously!
if(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)){
new httpAsynctask().execute();
}else{
Log.d("\nConnection State","Not connected to the net");
}
}
private class httpAsynctask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... aVoid) {
//Thank you for your help, please let me access Google
String site = "www.google.co.jp";
//= Set what kind of communication is performed =
//HTTP version 1.1 GET communication
//The connection destination host is Google!
//Close the connection after GET
String httpsocket = "GET / HTTP/1.1 \n" +
"Host: " + site + "\n" +
"Connection: close\n\n";
//A string buffer that stores Google-like HTML content
// socket :Connection
// BufferWriter :Accumulate the HTML to be read in the buffer
// BufferReader :Read HTML from buffer
StringBuffer stringBuffer = new StringBuffer();
Socket socket = null;
BufferedWriter writer = null;
BufferedReader reader = null;
try {
//In socket"www.google.co.jp",Set to port 80
//Set streams for writer and reader
//HTTP1 to writer.1 Read the HTML obtained by GET communication
socket = new Socket(site, 80);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer.write(httpsocket);
writer.flush();
//From the buffer written by the writer
//Read line by line with reader
while (reader.readLine() != null) {
stringBuffer.append(reader.readLine());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) writer.close();
if (reader != null) reader.close();
if (socket != null) socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuffer.toString();
}
@Override
protected void onPostExecute(String stringBuffer){
Log.d("\n START \n",stringBuffer);
}
}
}
For Socket communication, specify the FQDN (Fully Qualified Domain Name)!
HttpURLConnection
python
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Use with AsyncTask!
textView = findViewById(R.id.textView);
//First, check the status of your internet connection!
//Prepare network capabilities!
//You can check the connection with the capability hasTransport
// getSystemService(CONNECTIVITY_SERVICE)Get the object that manages the connection status with manager
//Connection management object getActiveNetwork()Get the active connection object in network
//Get network performance information for active connection objects capabilities
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
// getActiveNetwork()Is Manifest permission ACCESS_NETWORK_Requires STATE
Network network = manager.getActiveNetwork();
NetworkCapabilities capabilities = manager.getNetworkCapabilities(network);
//Check WIFI connection with capability hasTransport method
//Asynchronous communication only when connected to WIFI!
if(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
new httpAsyncTask().execute();
}else{
Log.d("\n\nMSG","no connect\n\n");
}
}
//Asynchronous communication AsyncTask<doInBackgroundURL,onProgressUpdateInteger...,onPostExecute(Result)>
private class httpAsyncTask extends AsyncTask<Void,Void,String> {
@Override
protected String doInBackground(Void... aVoid) {
//try clause catch clause finally declare the variables used in the clause!
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
StringBuffer stringBuffer = new StringBuffer();
try{
//Connection settings with HttpURLConnection!
urlConnection = (HttpURLConnection) new URL("https://google.co.jp").openConnection();
//Preparation for reading Google-like page information piled up in Buffer! InputStream()I will use!
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
//Time-consuming processing such as FileReader and InputStream should be wrapped in Buffer and used by reference
//Read line by line from Buffer and store in stringButter
while(reader.readLine() != null){
stringBuffer.append(reader.readLine());
}
}catch(Exception e){
return "MSG : FAILED TO CONNECT";
}finally{
try {
if(reader != null) reader.close();
if(urlConnection != null) urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
// onPostExecute()Send to
return stringBuffer.toString();
}
// doInBackground()Receives a string from and does something you want to do.
//Here you can write code to operate UI parts!
@Override
protected void onPostExecute(String stringBuffer){
textView.setText(stringBuffer);
}
}
}
--getSystemService (): Context method --CONNECTIVITY_SERVICE: Context constant
Recommended Posts