Android_Volley
15536 ワード
Volleyによるネットワーク通信
ネットワーク通信-クライアント/サーバ


Volley

動作原理

使用方法
Managestで次のキャッシュを使用してインターネット権限を設定します.

gradeの依存項目にライブラリを追加します.


アプリケーションソース
完全なソース
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
public class MainActivity extends AppCompatActivity {
Button btnRequest;
TextView tvResult;
EditText edtURL;
RequestQueue queue;
StringRequest request;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtURL = findViewById(R.id.editURL);
tvResult = findViewById(R.id.tvResult);
btnRequest = findViewById(R.id.btnRequest);
queue = Volley.newRequestQueue(MainActivity.this);
btnRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String URL = "https://" + edtURL.getText().toString();
request = new StringRequest(
Request.Method.GET,
URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
tvResult.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_SHORT).show();
}
}
);
queue.add(request);
}
});
}
}
ソース解析
要求と応答を宣言するオブジェクト
RequestQueue queue;
StringRequest request;
StringRequestオブジェクトの作成と初期化
request = new StringRequest(
Request.Method.GET,
URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
tvResult.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_SHORT).show();
}
}
);
New StringRequest(データ伝送方式、要求アドレス、応答リスナー、リスナー)
データ転送方式:GETまたはPOST
≪リクエスト・アドレス|Request Address|ldap≫:リクエストの数
ex)http:~ or https:~
≪レスポンス・リスナー|Response Listener|ldap≫:サーバーのレスポンス時に実行されるリスナー
public void onResponse(String response) {
tvResult.setText(response);
}
積極的な回答があれば、実行する内容を追加できます.エラーリスナー:エラーが発生したときに実行されるリスナーを要求または応答します.
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_SHORT).show();
}
否定的な回答があれば、実行する内容を追加できます.サーバにリクエストを送信する方法
queue.add(request);
実行画面

Reference
この問題について(Android_Volley), 我々は、より多くの情報をここで見つけました https://velog.io/@dfdf/Android-dm3yt8ohテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol