What is AsyncHttp
It is a plug-in on github, which is used to obtain network data. Its function is similar to that of HttpUrlConnection
This article is to translate and supplement the information in github documents.
Make a Static Http Client: create a static method (which can realize code reuse). Before importing the dependency package, you can see the previous code I circled. I believe you can understand it.
We use AsyncHttp to access network data:
Effect display
Code implementation:
1. Create a class and customize a public static decorated method
//Create a public class
public class HttpUtil {
//Define the unchanging part of a URL first. When a URL is transmitted, only the changed part is needed
private static final String basicUrl = "http://103.244.59.105:8014/paopaoserver/";
//Create AsyncHttpClient object
private static AsyncHttpClient client = new AsyncHttpClient();
//Create a method to apply for access to the network, and call callback method at the end.
public static void get(String url, RequestParams params, AsyncHttpResponseHandler asyncHttpResponseHandler){
client.get(getAbsulateUrl(url),params,asyncHttpResponseHandler);
}
//This method is used to add the invariant part of the URL + the changeable part of the URL
private static String getAbsulateUrl(String relativeUrl){
return basicUrl+relativeUrl;
}
}
2. When you need to access the network, call the get method to implement the callback method
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button showBtn;
private String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bangID();
}
private void bangID() {
showBtn = findViewById(R.id.main_show_btn);
showBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.main_show_btn:
//Create AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
//Call get method
client.get("https://www.csdn.net/", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Toast.makeText(MainActivity.this, "Failed to access network", Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
//Success
//Log.e(TAG, "onSuccess: "+responseString );
Toast.makeText(MainActivity.this, responseString, Toast.LENGTH_SHORT).show();
}
});
//Another way to start the network
//Create RequestParams object
// RequestParams requestParams = new RequestParams();
//Put parameters and values in requestParams as key value pairs
// requestParams.put("params","{\"classify_id\":70,\"page\":1,\"page_count\":2}");
// / / start up
// HttpUtil.get("categorylist",requestParams, new TextHttpResponseHandler() {
// @Override
// public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
// Toast.makeText(MainActivity.this, "failture", Toast.LENGTH_SHORT).show();
// }
//
// @Override
// public void onSuccess(int statusCode, Header[] headers, String responseString) {
// Log.e(TAG, "onSuccess: "+responseString );
// Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
//
// }
// });
break;
default:
}
}
}
Add: you can see that when we send a request, we use the get method, and the parameters are sent in the form of key value pairs. Then I will explain how to use the post method to transfer json data;
1. Add the post () method to our static method class
//Create a public class
public class HttpUtil {
//Define the unchanging part of a URL first. When a URL is transmitted, only the changed part is needed
private static final String basicUrl = "http://103.244.59.105:8014/paopaoserver/";
//Create AsyncHttpClient object
private static AsyncHttpClient client = new AsyncHttpClient();
//Create a method to apply for access to the network, and call callback method at the end.
public static void get(String url, RequestParams params, AsyncHttpResponseHandler asyncHttpResponseHandler){
client.get(getAbsulateUrl(url),params,asyncHttpResponseHandler);
}
//Create post method
public static void post(Context context, String url, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) {
client.post(context,url,entity,contentType,responseHandler);
}
//This method is used to add the invariant part of the URL + the changeable part of the URL
private static String getAbsulateUrl(String relativeUrl){
return basicUrl+relativeUrl;
}
}
2. Call the post method when you need to apply for the network
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button showBtn;
private String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bangID();
}
private void bangID() {
showBtn = findViewById(R.id.main_show_btn);
showBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.main_show_btn:
Intent intent = getIntent();
String basicUrl = intent.getStringExtra("basicUrl");
//Create a JSONObject array
final JSONObject[] jsonObject = {new JSONObject()};
try {
//By assigning a value to the object of the JSONObject array to pass the json data, you can add multiple
jsonObject[0].put("Blower",1);
} catch (JSONException e) {
e.printStackTrace();
}
//Create ByteArrayEntity object
ByteArrayEntity entity = null;
try {
entity = new ByteArrayEntity(jsonObject[0].toString().getBytes("UTF-8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpUtil.post(MainActivity.this, basicUrl + "control", entity, "application/json", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
}
});
break;
default:
}
}
}