* MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView textView;
static RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
textView = findViewById(R.id.textView);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String urlStr = editText.getText().toString();
request(urlStr);
}
});
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
public void request(String urlStr) {
StringRequest request = new StringRequest(
Request.Method.GET,
urlStr,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
println("응답 :" + response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
println("에러 : " + error.toString());
}
}
) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
request.setShouldCache(false);
requestQueue.add(request);
println("요청 보냄");
}
public void println(String data) {
textView.append(data + "\n");
}
}
* activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="http://www.google.com" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="요청" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView"
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
</LinearLayout>
* Gradle
dependencies {
implementation 'com.android.volley:volley:1.1.0'
}
* AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<application android:usesCleartextTraffic="true" />
'android' 카테고리의 다른 글
SQLite 사용법 (0) | 2020.02.05 |
---|---|
gson 사용법 (0) | 2020.02.04 |
HttpURLConnection 사용법 (0) | 2020.02.04 |
Socket 통신(Thread 필수) (0) | 2020.02.04 |
AsyncTask 사용법 (0) | 2020.02.04 |