Main7Activity.java
package com.example.m1;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
public class Main7Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main7);
volley_Get();
}
private void volley_Get() {
String url = "http://www.imooc.com/api/teacher?type=4&num=30";
/**
* StringRequest(int method, String url,
* Listener<String> listener, ErrorListener errorListener)
* @method 请求方法
* @url请求路径,
* @Listener请求成功的监听的回调,
* @ErrorListener请求失败的监听回调
*/
StringRequest request = new StringRequest(Request.Method.GET,url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("TAG", "onResponse:成功了");
Toast.makeText(Main7Activity.this,"请求成功volleyGetStringMonth"+response,
Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("TAG","onErrorResponse:失败了");
}
});
//设置请求标签用于加入全局队列后,方便找到
request.setTag("abcGet");
//加入到全局队列
MyApplication.getHttpQueues().add(request);
}
}
MyApplication.java
package com.example.m1;
import android.app.Application;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class MyApplication extends Application {
public static RequestQueue queues;
@Override
public void onCreate() {
super.onCreate();
queues = Volley.newRequestQueue(getApplicationContext());
}
/**
* 建立好请求队列
* @return
*/
public static RequestQueue getHttpQueues(){
return queues;
}
}
来源:https://blog.csdn.net/CCCrunner/article/details/98773084