HTTP GET
必須要用 thread 發送請求,且要包住 try catch
new Thread(new Runnable(){
@Override
public void run() {
try {
URL url = new URL("https://google.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
response.append('\r');
}
reader.close();
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
需要讀 stream 然後 append 到字串,如果是 JSON 要另外解析
包成 class
package com.example.myapplication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
public class Util {
public interface GenericMethod { // 讓呼叫可以使用 callback
public void call(String s);
}
public static String doGet(String _url, GenericMethod g) throws InterruptedException {
StringBuilder response = new StringBuilder();
Thread threadC = new Thread(() -> {
try {
URL url = new URL(_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
response.append('\r');
}
reader.close();
g.call(response.toString());
} catch (IOException e) {
e.printStackTrace();
}
});
threadC.start();
return response.toString();
}
}
main.java
package com.example.myapplication;
import android.os.Bundle;
import android.widget.Button;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = findViewById(R.id.button1);
b.setOnClickListener(view -> {
try {
Util.doGet("https://tw.yahoo.com", (String s) -> {
System.out.println(s);
});
} catch (InterruptedException e){
System.out.println(e);
}
});
}
}
使用 volley
Last updated
Was this helpful?