1-usul: Maxsus sinflarni yaratish



Download 0,65 Mb.
Sana31.12.2021
Hajmi0,65 Mb.
#241782
Bog'liq
2 5301277738315813406

1-usul: Maxsus sinflarni yaratish

Biz yaratadigan birinchi sinf RequestPackage klassi deb nomlanadi. Ushbu sinf HTTP so'rovlarini bajarishda uchta muhim qiymatni qabul qiladi. Birinchidan, u URL manzilini oladi.

public class RequestPackage {

private String url;

private String method = "GET"; //method is set to GET by default

private Map params = new HashMap<>();//This will hold any values

//that the server may require

// e.g. product_id

public String getUrl() {

return url;

}

public void setUrl(String url) {



this.url = url;

}


public String getMethod() {

return method;

}

public void setMethod(String method) {



this.method = method;

}


public Map 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();

}

});



}

}






Download 0,65 Mb.

Do'stlaringiz bilan baham:




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish