Biz yaratadigan birinchi sinf RequestPackage klassi deb nomlanadi. Ushbu sinf HTTP so'rovlarini bajarishda uchta muhim qiymatni qabul qiladi. Birinchidan, u URL manzilini oladi.
// e.g. product_id
getParams() {
return params;
}
public void setParams(Map params) {
this.params = params;
}
public void setParam(String key, String value) {
params.put(key, value); //adds a single value to the params member variable
}
//The method below is only called if the request method has been set to GET
//GET requests sends data in the url and it has to be encoded correctly in order
//for the server to understand the request. This method encodes the data in the
//params variable so that the server can understand the request
public String getEncodedParams() {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
try {
value = URLEncoder.encode(params.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
return sb.toString();
}
}
HttpManager
Keyinchalik, biz HttpManager sinfini yaratamiz.
public class HttpManager {
public static String getData(RequestPackage requestPackage) {
BufferedReader reader = null;
String uri = requestPackage.getUrl();
if (requestPackage.getMethod().equals("GET")) {
uri += "?" + requestPackage.getEncodedParams();
//As mentioned before, this only executes if the request method has been
//set to GET
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(requestPackage.getMethod());
if (requestPackage.getMethod().equals("POST")) {
con.setDoOutput(true);
OutputStreamWriter writer =
new OutputStreamWriter(con.getOutputStream());
writer.write(requestPackage.getEncodedParams());
writer.flush();
}
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
}
Barchasini birlashtirish
public class MainActivity extends AppCompatActivity {
private TextView mPriceTextView;
private String BASE_URL = "https://apiv2.bitcoinaverage.com/indices/global/ticker/BTC";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPriceTextView = (TextView) findViewById(R.id.priceLabel);
Button btnUSD = (Button) findViewById(R.id.btnUSD);
Button btnZAR = (Button) findViewById(R.id.btnZAR);
Button btnAUD = (Button) findViewById(R.id.btnAUD);
//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in USD
btnUSD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "USD");
}
});
//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in ZAR
btnZAR.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "ZAR");
}
});
//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in AUD
btnAUD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "AUD");
}
});
}
private void requestData(String url) {
RequestPackage requestPackage = new RequestPackage();
requestPackage.setMethod("GET");
requestPackage.setUrl(url);
Downloader downloader = new Downloader(); //Instantiation of the Async task
//that’s defined below
downloader.execute(requestPackage);
}
private class Downloader extends AsyncTask {
@Override
protected String doInBackground(RequestPackage... params) {
return HttpManager.getData(params[0])
}
//The String that is returned in the doInBackground() method is sent to the
// onPostExecute() method below. The String should contain JSON data.
@Override
protected void onPostExecute(String result) {
try {
//We need to convert the string in result to a JSONObject
JSONObject jsonObject = new JSONObject(result);
//The “ask” value below is a field in the JSON Object that was
//retrieved from the BitcoinAverage API. It contains the current
//bitcoin price
String price = jsonObject.getString("ask");
//Now we can use the value in the mPriceTextView
mPriceTextView.setText(price);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
2-usul: Android Asynchronous HTTP Client
App / build.gradle fayliga o'ting va bog'liqliklar bo'limiga quyidagi kodni kiriting:
public class MainActivity extends AppCompatActivity {
private TextView mPriceTextView;
private String BASE_URL = "https://apiv2.bitcoinaverage.com/indices/global/ticker/BTC";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPriceTextView = (TextView) findViewById(R.id.priceLabel);
Button btnUSD = (Button) findViewById(R.id.btnUSD);
Button btnZAR = (Button) findViewById(R.id.btnZAR);
Button btnAUD = (Button) findViewById(R.id.btnAUD);
//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in USD
btnUSD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "USD");
}
});
//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in ZAR
btnZAR.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "ZAR");
}
});
//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in AUD
btnAUD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "AUD");
}
});
}
private void requestData(String url) {
//Everything below is part of the Android Asynchronous HTTP Client
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
// called when response HTTP status is "200 OK"
Log.d("Bitcoin", "JSON: " + response.toString());
try {
//The “ask” value below is a field in the JSON Object that was
//retrieved from the BitcoinAverage API. It contains the current
//bitcoin price
String price = response.getString("ask");
//Now we can use the value in the mPriceTextView
mPriceTextView.setText(price);
} catch (Exception e) {
Log.e("Bitcoin", e.toString());
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable e,
JSONObject response) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
Log.d("Bitcoin", "Request fail! Status code: " + statusCode);
Log.d("Bitcoin", "Fail response: " + response);
Log.e("ERROR", e.toString());
Toast.makeText(MainActivity.this, "Request Failed",
Toast.LENGTH_SHORT).show();
}
});
}
}
Do'stlaringiz bilan baham: