How do you upload a video (.mp4) file in the raw folder to a server on a button click in java android studio with minSdk 29.
Any help with this would be much appreciated.
This is what I have tried:
private void configureUploadButton() {
uploadButton = findViewById(R.id.uploadButton);
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// creating a client
OkHttpClient okHttpClient = new OkHttpClient();
int videoResourceId = getResources().getIdentifier("name_of_video", "raw", getPackageName());
Uri fileUri = Uri.parse("android.resource://" + getPackageName() + "/" + videoResourceId);
Log.i("URI", "File URI: " + fileUri);
File videoFile = new File(fileUri.getPath());
Log.i("FILE_TAG", "File: " + videoFile + " Path: " + videoFile.getPath());
RequestBody requestBody = RequestBody.create(MediaType.parse("video/mp4"), videoFile);
MultipartBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("video", videoFile.getName(), requestBody)
.build();
Request request = new Request.Builder()
.url("http://10.0.2.2:5000/upload_video")
.post(multipartBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("SERVER_DOWN", "The sever is down: " + e.getMessage());
Toast.makeText(Record.this, "server down", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
int responseCode = response.code();
String responseMessage = response.message();
Log.i("RESPONSE", "Response code: " + responseCode + " Message: " + responseMessage);
if (response.isSuccessful()) {
Toast.makeText(Record.this, "Connected to server successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Record.this, "Not able to connect to server.", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
});
}
I don't seem to be accessing the file correctly using the File class. The IOException that I am getting in the onFailure of the okHttpClient call is:
/2131689473: open failed: ENOENT (No such file or directory)
These are the permissions that I have in my Androidmanifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.hardware.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
You will acces app data specific folder through " getExternalFilesDir() "
and your application data available in " sdcard =>Android => package.name => file.mp4 "
APIClient.java
public class APIClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.hostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
})
.addInterceptor(interceptor)
.build();
retrofit = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:5000")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
}
APIInterface.java
public interface APIInterface {
#Multipart
#POST("/api/UploadVideo")
Call<VideoUpload> chequeUpload(
#Part MultipartBody.Part video);
}
Model Class
public class VideoUpload {
// Request
#SerializedName("video")
public String video;
// Response
#SerializedName("Message")
public String Message;
}
Upload video
video get from " Android " Specific folder sdcard =>Android => package.name => file.mp4
code.
String root = getExternalFilesDir("/").getPath() + "/" + "Videos/";
File videoFile = new File(root, "My_video" + ".mp4");
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), videoFile);
MultipartBody.Part videoFileBody = MultipartBody.Part.createFormData("video", videoFile.getName(), requestFile);
Call<VideoUpload> call = apiInterface.videoUploadNow(videoFileBody);
call.enqueue(new Callback<VideoUpload>() {
#Override
public void onResponse(#NonNull Call<VideoUpload> call, #NonNull Response<VideoUpload> response) {
pDialog.dismiss();
if (response.isSuccessful()){
VideoUpload uploadVideo = response.body();
try {
JSONObject jsonObjectError = new JSONObject(response.errorBody().string());
showMessageInSnackbar(jsonObjectError.getString("Message"));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
JSONObject jsonObjectError = new JSONObject(response.errorBody().string());
showMessageInSnackbar(jsonObjectError.getString("Message"));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(#NonNull Call<VideoUpload> call, #NonNull Throwable t) {
if(t instanceof SocketTimeoutException){
timeOutDialog.show();
}
pDialog.dismiss();
}
});
Related
I am simply trying to implement stripe payments in my app and i am following the their doc here https://stripe.com/docs/payments/quickstart and i keep getting this error ( Failed to connect to localhost/127.0.0.1:4242) , whenever i launch my app. I am not sure why this is happening i already tried adding android:usesCleartextTraffic="true" to my manifest file as some users suggested but to no avail.
public class payment_activity extends AppCompatActivity {
private String paymentIntentClientSecret;
private PaymentLauncher paymentLauncher;
// we need paymentIntentClientSecret to start transaction
private Button paymentButton;
CardInputWidget cardInputWidget;
private PaymentSheet paymentSheet;
private static final String TAG = "CheckoutActivity";
private static final String BACKEND_URL = "http://localhost:4242";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
paymentButton = findViewById(R.id.payButton);
cardInputWidget = findViewById(R.id.cardInputWidget);
paymentSheet = new PaymentSheet(this, this::onPaymentSheetResult);
fetchPaymentIntent();
paymentButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PaymentSheet.Configuration configuration = new PaymentSheet.Configuration("Example, Inc.");
// Present Payment Sheet
paymentSheet.presentWithPaymentIntent(paymentIntentClientSecret, configuration);
}
});
}
private void showAlert(String title, #Nullable String message) {
runOnUiThread(() -> {
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton("Ok", null)
.create();
dialog.show();
});
}
private void showToast(String message) {
runOnUiThread(() -> Toast.makeText(this, message, Toast.LENGTH_LONG).show());
}
private void fetchPaymentIntent() {
final String shoppingCartContent = "{\"items\": [ {\"id\":\"xl-tshirt\"}]}";
final RequestBody requestBody = RequestBody.create(
shoppingCartContent,
MediaType.get("application/json; charset=utf-8")
);
Request request = new Request.Builder()
.url(BACKEND_URL + "/create-payment-intent")
.post(requestBody)
.build();
new OkHttpClient()
.newCall(request)
.enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
showAlert("Failed to load data", "Error: " + e.toString());
}
#Override
public void onResponse(
#NonNull Call call,
#NonNull Response response
) throws IOException {
if (!response.isSuccessful()) {
showAlert(
"Failed to load page",
"Error: " + response.toString()
);
} else {
final JSONObject responseJson = parseResponse(response.body());
paymentIntentClientSecret = responseJson.optString("clientSecret");
runOnUiThread(() -> paymentButton.setEnabled(true));
Log.i(TAG, "Retrieved PaymentIntent");
}
}
});
}
private JSONObject parseResponse(ResponseBody responseBody) {
if (responseBody != null) {
try {
return new JSONObject(responseBody.string());
} catch (IOException | JSONException e) {
Log.e(TAG, "Error parsing response", e);
}
}
return new JSONObject();
}
private void onPaymentSheetResult(
final PaymentSheetResult paymentSheetResult
) {
if (paymentSheetResult instanceof PaymentSheetResult.Completed) {
showToast("Payment complete!");
} else if (paymentSheetResult instanceof PaymentSheetResult.Canceled) {
Log.i(TAG, "Payment canceled!");
} else if (paymentSheetResult instanceof PaymentSheetResult.Failed) {
Throwable error = ((PaymentSheetResult.Failed) paymentSheetResult).getError();
showAlert("Payment failed", error.getLocalizedMessage());
}
}
}
Faild to connect to localhost/127.0.0.1:4242
I connect to localhost:4242 in my Android apps using the following URL inside Android Studio: http://10.0.2.2:4242
Update your BACKEND_URL constant and give that a try.
I am trying to upload an image to server using volley, I followed some tutorials but in my case, I need to pass the multipart data in the body of the post request.
private void uploadBitmap(final Bitmap bitmap) throws JSONException {
//our custom volley request
String URL = "https://<---------->/me/avatar";
JSONObject jsonBody = new JSONObject();
jsonBody.put("avatar", new VolleyMultipartRequest.DataPart( "index.png", getFileDataFromDrawable(bitmap)));
final String requestBody = jsonBody.toString();
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, URL,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
loading.setVisibility(View.GONE);
Toast.makeText(ProfileSettings.this, "Image uploaded successfully", Toast.LENGTH_SHORT).show();
try {
JSONObject obj = new JSONObject(new String(response.data));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Bearer " + jsonToken);
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
params.put("avatar", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
return params;
}
#Override
public byte[] getBody() throws AuthFailureError {
return requestBody.getBytes();
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
I got this code from tutorials, but they are giving 500 error, so I guess this may be because I need to pass "avatar": "index.png" in the body of the request and not this way.
follow these link - https://www.simplifiedcoding.net/upload-image-to-server/
https://www.simplifiedcoding.net/android-upload-image-to-server/
and also use this library to upload image and file - https://github.com/gotev/android-upload-service.
please follow the above tutorial give introduce these libraries.
I was able to achieve this using retrofit 2, here's the code.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
//getting the image Uri
Uri imageUri = data.getData();
try {
//getting bitmap object from uri
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
//displaying selected image to imageview
logo.setImageBitmap(bitmap);
//calling the method uploadBitmap to upload image
loading.setVisibility(View.VISIBLE);
///uploadBitmap(bitmap);
File file = new File(getRealPathFromUri(this, imageUri));
uploadImageFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private void uploadImageFile(File file) throws IOException {
file = new Compressor(this).compressToFile(file);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
// MultipartBody.Part is used to send also the actual filename
MultipartBody.Part body = MultipartBody.Part.createFormData("avatar", file.getName(), requestFile);
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<ServerResponse> call = getResponse.uploadFile("Bearer "+jsonToken, body);
call.enqueue(new Callback< ServerResponse >() {
#Override
public void onResponse(#NonNull Call < ServerResponse > call, #NonNull retrofit2.Response<ServerResponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse.getData() != null) {
Log.e(TAG, "Response is "+ serverResponse.getData());
loading.setVisibility(View.GONE);
Toast.makeText(ProfileSettings.this, "Avatar updated", Toast.LENGTH_SHORT).show();
} else {
Log.e("Response", String.valueOf(serverResponse));
}
}
#Override
public void onFailure(Call < ServerResponse > call, Throwable t) {
Log.e(TAG, t.getMessage());
}
});
// Log.e(TAG, "request is "+call.request().body()+" and "+call.request().headers());
}
The first URL returns a list of names and IDs of farmers markets:
https://search.ams.usda.gov/farmersmarkets/v1/data.svc/locSearch?lat=" + latitude + "&lng=" + longitude
Then, the ID from the above URL must be used to get further information from each farmers market:
"https://search.ams.usda.gov/farmersmarkets/v1/data.svc/mktDetail?id=" + id
I want to display the name of the farmers markets from the first URL, and then the address of each farmers market from the second URL. How can I do this so that it all proceeds in the correct order?
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private ListView mListView;
GPSTracker gps;
Context mContext;
String marketAddress;
ArrayList<String> marketAddressArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView = (ListView) findViewById(R.id.list_view);
double latitude = 45.496481;
double longitude = -122.573462;
gps = new GPSTracker(mContext, MainActivity.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
else {
gps.showSettingsAlert();
}
final String marketUrl = "https://search.ams.usda.gov/farmersmarkets/v1/data.svc/locSearch?lat=" + latitude + "&lng=" + longitude;
Log.d(TAG, String.valueOf(latitude));
Log.d(TAG, String.valueOf(longitude));
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(marketUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
Log.d(TAG, "failure");
}
#Override
public void onResponse(Response response) throws IOException {
try {
final String jsonData = response.body().string();
Log.v(TAG, "THIS IS MY JSONDATA " + jsonData);
if (response.isSuccessful()) {
Log.d(TAG, marketUrl);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
getCurrentDetails(jsonData);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Log.v(TAG, jsonData);
}
}
catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
Log.d(TAG, "Main UI code is running!");
}
private void getCurrentDetails(String jsonData) throws JSONException {
JSONObject usdaJSON = new JSONObject(jsonData);
JSONArray resultsJSON = usdaJSON.getJSONArray("results");
Market[] markets = new Market[resultsJSON.length()];
for(int i = 0; i < resultsJSON.length(); i++){
final JSONObject marketJSON = resultsJSON.getJSONObject(i);
String marketname = marketJSON.getString("marketname");
String id = marketJSON.getString("id");
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://search.ams.usda.gov/farmersmarkets/v1/data.svc/mktDetail?id=" + id)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
Log.d(TAG, "failure");
}
#Override
public void onResponse(Response response) throws IOException {
try {
final String marketDetailsJsonData = response.body().string();
Log.v(TAG, "THIS IS MY JSONDATA " + marketDetailsJsonData);
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject detailsJSON = new JSONObject(marketDetailsJsonData);
JSONObject marketDetailsJSON = detailsJSON.getJSONObject("marketdetails");
marketAddress = marketDetailsJSON.getString("Address");
marketAddressArrayList.add(marketAddress);
//marketAddressArrayList.get(0);
//updateMarketAddress(); call this method for each market found - it will run 20 times if there are 20 markets
Log.d(TAG, "this is marketadress"+ marketAddress);
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "broken");
}
}
});
}
}
catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
Log.d(TAG, "outside of the loop"+ marketname);
Market market = new Market(marketname, id, marketAddress);
markets[i] = market;
//markets[i].setAddress(marketAddressArrayList.get(i));
}
MarketAdapter adapter = new MarketAdapter(this, markets);
mListView.setAdapter(adapter);
for(int i = 0; i < resultsJSON.length(); i++) {
Log.d(TAG, markets[i].getMarketname());
Log.d(TAG, markets[i].getId());
// Log.d(TAG, markets[i].getMarketAddress());
}
}
}
First, extract out all the JSON parsing (for example, use Retrofit instead of OkHTTP) and UI updating to a separate method.
Then, hit the first URL, from that onResponse, hit the second URL.
Basically, what you are doing now,
if (response.isSuccessful()) {
Log.d(TAG, marketUrl);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
getCurrentDetails(jsonData); // Call the second URL
But it doesn't need to be on the UI thread if you aren't updating the UI
Your for loop at the end must be within the second onResponse body, where the adapter/list would be populated.
Also, MarketAdapter should probably use List<Market> instead of ArrayList<String>
I'm new to android development but I'm stuck on why I can make calls to my API, but it doesn't populate my class in time for the recycler view to populate. I get IndexOutOfBoundsException because the mData.getDataFeeds() returns null. If I debug this application and walk through it slowly, it works.
ListFeedAdapter listFeedAdapter = new ListFeedAdapter(mData.getDataFeeds());
I have an Activity that gets a Fragment.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
try {
login();
getFeed();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
ListFeedAdapter listFeedAdapter = new ListFeedAdapter(mData.getDataFeeds());
recyclerView.setAdapter(listFeedAdapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
return view;
}
Then I call login()
private void login() throws IOException {
String user = "user";
String password = "pass";
String loginUrl = getString(R.string.jsonLogin);
OkHttpClient client = new OkHttpClient.Builder()
.build();
JSONObject credentials = new JSONObject();
JSONObject session = new JSONObject();
try {
credentials.put("email", user);
credentials.put("password", password);
session.put("session", credentials);
} catch (JSONException e) {
e.printStackTrace();
}
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, session.toString());
Request request = new Request.Builder()
.url(loginUrl)
.post(body)
.addHeader("Content-Type", mediaType.toString())
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
String jsonData = response.body().string();
String jsonHead = response.headers("Set-Cookie").toString();
if(response.isSuccessful()) {
for (String setCookie : response.headers("Set-Cookie")) {
cookies.add(Cookie.parse(response.request().url(), setCookie));
}
}
}
});
The getFeed()
private void getFeed() throws IOException, JSONException {
String loginUrl = "http://testurlhere";
OkHttpClient client = new OkHttpClient.Builder()
.build();
MediaType mediaType = MediaType.parse("application/json");
Request request = new Request.Builder()
.url(loginUrl)
.get()
.addHeader("Content-Type", mediaType.toString())
.addHeader("_session", cookies.get(0).toString())
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonData = response.body().string();
String jsonHead = response.headers("Set-Cookie").toString();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mData = parseDataFeed(jsonData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
}
}
catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
}
okhttp is an asynchronous operation, and you should use mData after onResponse ()
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonData = response.body().string();
String jsonHead = response.headers("Set-Cookie").toString();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mData = parseDataFeed(jsonData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
ListFeedAdapter adapter = new ListFeedAdapter(mData.getDataFeeds());
rexyxlerView.setAdapter(adapter);
updateDisplay();
}
});
}
}
catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
I'm new to android programming, and I wanted to make a small program to download strings from a specific API-URL. (I'm not new to the programming overall).
Now I'm stuck with the following code, just to download my string from url:
String urlToDownloadToken = baseUrl + "?action=login&username=xxx&password=xxx";
Object taskResult = new DownloadString().execute(urlToDownloadToken);
The implementation of the download class is as following. In the callbnack function I have a toast that should theoretically display the Data, but it always makes an emty toast (The code I have found is from here: https://stackoverflow.com/a/14418213):
Edit: Full source after applying recommendation to use OkHttp
public class MusicScroll extends AppCompatActivity {
String baseUrl = "http://ppcinj.com";
String token = "";
AlertDialog.Builder dlgAlert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_scroll);
//Set MessageBox properties...
dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setCancelable(true);
dlgAlert.setTitle("Message from Application");
dlgAlert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
try {
String urlToDownloadToken = baseUrl + "?action=login&username=xxx&password=xxx";
token = downloadString(urlToDownloadToken);
} catch (Exception e) {
dlgAlert.setMessage("Error downloading data: " + e.getMessage());
dlgAlert.create().show();
}
dlgAlert.setMessage(token);
dlgAlert.create().show();
}
OkHttpClient client = new OkHttpClient();
String downloadString(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
Is there any way I could download as simple as with C#'s WebClient?
Kind regards :)
Edit 2: Got it to work with the following code :)
public class MusicScroll extends AppCompatActivity {
String baseUrl = "http://ppcinj.tk:5656";
String token = "";
AlertDialog.Builder dlgAlert;
Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message message) {
if (message.what == 1) {
Toast.makeText(getApplicationContext(), token, Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_scroll);
//Set MessageBox properties...
dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setCancelable(true);
dlgAlert.setTitle("Message from Application");
dlgAlert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
try {
String urlToDownloadToken = baseUrl + "?action=login&username=michael&password=qwerty123";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(urlToDownloadToken)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.e("BNK", e.toString());
}
#Override
public void onResponse(Response response) throws IOException {
Log.i("BNK", response.toString());
token = response.body().string();
Message msg = mHandler.obtainMessage(1);
msg.sendToTarget();
}
});
} catch (Exception e) {
dlgAlert.setMessage("Error downloading data: " + e.getMessage());
dlgAlert.create().show();
}
}
public void showToken()
{
Toast.makeText(getApplicationContext(), token, Toast.LENGTH_LONG).show();
}
}
HttpClient has been deprecated for years and has been removed from Android 6. You should use OkHttp instead, it's the new standard. And it is a lot easier :).
You can refer to the following sample code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://ppcinj.com?action=login&username=michael&password=qwerty123")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.e("BNK", e.toString());
}
#Override
public void onResponse(Response response) throws IOException {
Log.i("BNK", response.toString());
}
});
}
}
Here is the screenshot of logcat
Hope this helps!