# HTTP GET

必須要用 thread 發送請求，且要包住 try catch

```java
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 要另外解析

{% embed url="<https://dotblogs.com.tw/newmonkey48/2017/09/21/152425>" %}

### 包成 class

```java
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&#x20;

```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);
            }
        });
    }
}
```

<https://stackoverflow.com/a/9148954/4622645>

## 使用 volley

{% embed url="<https://developer.android.com/training/volley/request>" %}

> If the response is in JSON format, use any third-party JSON parsers such as [*Jackson* ](https://www.baeldung.com/jackson)library, [*Gson*](https://www.baeldung.com/gson-string-to-jsonobject), or [*org.json*](https://www.baeldung.com/java-org-json) to parse the response.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://easonwang.gitbook.io/android/cheng-shi-xiang-guan/http-get.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
