i am using sinch from java, i recently reput credit to the account, and now when i try to send message i get succes message, but the sms isn't send. Following the link https://messagingapi.sinch.com/v1/sms/162393899 i get this
{"errorCode":40107,"message":"Invalid authorization key:
vivi******#gmail.com","reference":"BA:vivi******#gmail.com_GtIfKPDMJEKL4VJWR0kkJQ"}
the code
try {
String phoneNumber = "+40732******";
String appKey = "*****";
String appSecret = "****";
String message = "Test";
URL url = new URL("https://messagingapi.sinch.com/v1/sms/" + phoneNumber);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
String userCredentials = "application\\" + appKey + ":" + appSecret;
byte[] encoded = Base64.encodeBase64(userCredentials.getBytes());
String basicAuth = "Basic " + new String(encoded);
connection.setRequestProperty("Authorization", basicAuth);
String postData = "{\"Message\":\"" + message + "\"}";
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
StringBuilder response = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ( (line = br.readLine()) != null)
response.append(line);
br.close();
os.close();
System.out.println(response.toString());
} catch (IOException e) {
e.printStackTrace();
}
I am getting { "status": "failure", "code": 3, "host": "coreapp-devplatform-devapi-173", "generated_at": "Tue, 29 Sep 2015 05:42:42 +0000", "message": "Authorization failed.", "data": null } exception while invoking https://api.pinterest.com/v1/oauth/token?code=&client_id=&grant_type=authorization_code. Can anyone help me to resolve this?
Code:
if (request.getParameter("code") != null) {
code = request.getParameter("code");
}
String authorizeUrl = "https://api.pinterest.com/v1/oauth/token";
String postStr = "code=" + code + "&client_id=" + clientId + "&grant_type=authorization_code";
String responseStr = postTokenRequest(authorizeUrl, postStr);
//Method
public String postTokenRequest(String serverURL, String content) {
String inputLine = "";
HttpsURLConnection connection = null;
URL url = new URL(serverURL);
String method = "POST";
InputStream connectionIn = null;
BufferedReader buffer = null;
try {
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length));
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.getOutputStream().write(content.getBytes());
int returnCode = connection.getResponseCode();
if (returnCode == 200) {
connectionIn = connection.getInputStream();
} else {
connectionIn = connection.getErrorStream();
}
buffer = new BufferedReader(new InputStreamReader(connectionIn));
StringBuilder sb = new StringBuilder();
while ((inputLine = buffer.readLine()) != null) {
sb.append(inputLine);
}
buffer.close();
return sb.toString();
}catch(Exception e){}
}
I am trying to upload an audio file using the following code on server.Right now, it works perfectly well for image files but not for audios.I think MultipartFile should work with audio files as well.Can any one tell me what is wrong here?
I am getting "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method." error.
Does MultipartFile not work with audio files?If no what is an alternative?
#Transactional
public BaseVO uploadImage(MultipartFile file, long userId){
Map<String, Object> alertParams = new HashMap<String, Object>();
try{
if (!file.isEmpty()) {
Image profileImage = imageRepository.findByUserId(userId);
if(profileImage == null){
profileImage = new Image();
profileImage.setUserId(userId);
}
File dir = null;
String realPath;
if(liveBuild == "true"){
realPath = liveImageUploadRepository;
dir = new File(realPath);
}else{
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
realPath = request.getSession().getServletContext().getRealPath("/") + devImageUploadRepository;
dir = new File(realPath);
}
if (!dir.exists()) {
dir.mkdirs();
}
String finalFileStorePath = realPath + "/" + userId + ".jpg";
File path = new File(finalFileStorePath);
file.transferTo(path);
profileImage.setImagePath(realPath);
//profileImage.setImageName(userId + ".jpg");
profileImage.setImageName(userId+"");
profileImage.setImageType(".jpg");
imageRepository.save(profileImage);
alertParams.put("id", profileImage.getId());
} else {
return new BaseVO(alertParams, Constants.STATUS_OK, Constants.STATUS_OK_MSG);
}
}catch(HibernateException e){
return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG + " " + e.getMessage());
} catch (IllegalStateException e) {
e.printStackTrace();
return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG);
} catch (IOException e) {
e.printStackTrace();
return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG);
}
return new BaseVO(alertParams, Constants.STATUS_OK, Constants.STATUS_OK_MSG);
}
I am trying to use the SkyDrive API to upload a file. I tried using the below code.GEtAccountInformaiton and GetQuotaInformaiton methods are successfully executed But it always sets this error "The request has already been submitted.” at the end (in UploadISOFileToSkyDriveAsync() method for the field lblMessageBar.Text ).
private async void GetAccountInformations()
{
try
{
LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me");
var jsonResult = operationResult.Result as dynamic;
string firstName = jsonResult.first_name ?? string.Empty;
string lastName = jsonResult.last_name ?? string.Empty;
lblMessageBar.Text = "Welcome " + firstName + " " + lastName;
GetQuotaInformations();
}
catch (Exception e)
{
lblMessageBar.Text = e.ToString();
}
}
private async void GetQuotaInformations()
{
try
{
LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me/skydrive/quota");
var jsonResult = operationResult.Result as dynamic;
quota = jsonResult.quota ?? string.Empty;
available = jsonResult.available ?? string.Empty;
lblMessageBar.Text = "Available space in bytes: " + ConvertBytesToGigabytes(available).ToString("#.####") + "GB " + "out of bytes " + ConvertBytesToGigabytes(quota).ToString("#.####") + "GB";
UploadISOFileToSkyDriveAsync();
}
catch (Exception e)
{
lblMessageBar.Text = e.ToString();
}
}
public async void UploadISOFileToSkyDriveAsync()
{
try
{
//http://developer.nokia.com/Community/Wiki/SkyDrive_-_How_to_upload_content_on_Windows_Phone
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.Append, fileStorage));
//get the data from local database and write to the isolated file and then use the path of this file to saved it to skydrive..
ObservableCollection<SavedLocationsTableEntity> SavedLocations = SavedLocationsTableEntity.GetSavedLocations();
foreach (SavedLocationsTableEntity item in SavedLocations)
{
Writer.WriteLine(UtilityLib.GetGoogleURL(new System.Device.Location.GeoCoordinate(item.SavedLocationLatitude, item.SavedLocationLongitude, item.SavedLocationAltitude)));
}
Writer.Close();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
fileStream = store.OpenFile("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.OpenOrCreate, FileAccess.Read);
//strEncryptedFileStream = Encoding.Unicode.GetBytes(fileStream.ToString()).ToString();
if (fileStream.Length == 0)
{
lblMessageBar.Text = "No data to upload to SkyDrive..";
return;
}
fileStream.Close();
}
//remove previous calls
var reqList = BackgroundTransferService.Requests.ToList();
foreach (var req in reqList)
{
if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore, UriKind.Relative)))
BackgroundTransferService.Remove(BackgroundTransferService.Find(req.RequestId));
}
//Make a new call to upload
LiveOperationResult res = await App.liveConnectClient.BackgroundUploadAsync("me/skydrive", new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative), OverwriteOption.Overwrite);
lblMessageBar.Text = "File " + Constants.SkyDriveSavedLocationsFileName + " uploaded.";
return;
}
catch (Exception ex)
{
lblMessageBar.Text = "Cannot upload to SkyDrive.. " + ex.Message;
return;
}
}
It looks like MyFilePathInIsoStore here:
if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore
is not equals "/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName here:
new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative)
I just wanna ask if it is possible to use my customize toast in onPostExecute of my Asyntask in android. If yes then how? I tried to put it on the onPostExecute but I got a lot red lines. Here is my code for my customize toast:
Typeface tfR= Typeface.createFromAsset(getAssets(), "Gothic_Regular.TTF");
LayoutInflater inflater = getLayoutInflater();
View layouttoast = inflater.inflate(R.layout.toast_bg, (ViewGroup)findViewById(R.id.toastAttribute));
TextView msg = ((TextView) layouttoast.findViewById(R.id.txt_toast));
msg.setTypeface(tfR);
msg.setText(toast_msg);
msg.setTextSize(TypedValue.COMPLEX_UNIT_PX,16);
Toast mytoast = new Toast(getBaseContext());
mytoast.setView(layouttoast);
mytoast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
mytoast.setDuration(Toast.LENGTH_SHORT);
mytoast.show();
Then I want to put it here:
public class DoPost extends AsyncTask<String, Void, Boolean>
{
Exception exception = null;
Context mContext = null;
. . . . .
public DoPost(Context context, String username, String password,
String reportcode, String remarks, String date, String province,
String infotype, String competitor, ArrayList<String> brands,
ArrayList<String> segments)
{
mContext = context;
. . . .
databaseHandler = new DatabaseHandler(context);
if (databaseHandler != null)
{
databaseHandler.close();
databaseHandler.createDB();
}
}
protected void onPreExecute()
{
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Uploading attachment details....");
progressDialog.show();
progressDialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... arg0)
{
try {
JSONObject jObject = new JSONObject();
Log.d("DoPost Constants.FILE_URI", Constants.FILE_URI.toString());
Log.d("DoPost create SELECTEDFILE URI", SelectedFiles.listFileUri.toString());
Log.d("DoPost create SELECTEDFILE FILENAME", SelectedFiles.listFileName.toString());
// String filename = "Chapt-19.pdf";
String filename = "";
try {
JSONArray jArraySubrands = new JSONArray();
JSONArray jArrayConsumerSegments = new JSONArray();
JSONArray jArrayReportUpload = new JSONArray();
for (int i = 0; i < Constants.SHARED_PREFERENCES_SUBBRANDS.size(); i++)
{
JSONObject brand = new JSONObject();
brand.put("Id", _brands.get(i));
jArraySubrands.put(brand);
}
for (int j = 0; j < Constants.SHARED_PREFERENCES_SEGMENTS.size(); j++)
{
JSONObject consumerSegments = new JSONObject();
consumerSegments.put("Id", _segments.get(j));
jArrayConsumerSegments.put(consumerSegments);
}
for (int i = 0; i < Constants.ARRAYLIST_FILENAME.size(); i++)
{
JSONObject jObjectReportUpload = new JSONObject();
filename = Constants.ARRAYLIST_FILENAME.get(i);
jObjectReportUpload.put("ReportUploadId", 0);
jObjectReportUpload.put("Filename", filename);
jObjectReportUpload.put("TempFilename", filename);
jObjectReportUpload.put("Description", "Image Testing");
jObjectReportUpload.put("ReportUploadTypeId", 1);
jObjectReportUpload.put("ReportId", 0);
jArrayReportUpload.put(jObjectReportUpload);
Log.d("filename: ", filename);
}
jObject.put("ReportId", 0);
jObject.put("ReportCode", _code);
jObject.put("Title", "Mobile Developer");
jObject.put("Remarks", _remarks);
jObject.put("DateObserved", _date);
jObject.put("ProvinceId", _province);
jObject.put("InformationTypeId", _infotype);
jObject.put("ReportTypeId", 1);
jObject.put("IsCompetitor", _competitor);
jObject.put("SubBrands", jArraySubrands);
jObject.put("ConsumerSegments", jArrayConsumerSegments);
jObject.put("ReportUploads", jArrayReportUpload);
} catch (Exception e)
{
e.printStackTrace();
}
ResponseHandler<String> resonseHandler = new BasicResponseHandler();
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpPost httpPost = new HttpPost("http://phsjghhghghulchghg4.hgh.com:1214/api/reports");
HttpClient httpclient = new DefaultHttpClient(httpParameters);
httpPost.addHeader("Authorization","Basic "+ Base64.encodeToString((_username + ":" + _password).getBytes(),Base64.NO_WRAP));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new ByteArrayEntity(jObject.toString().getBytes(HTTP.UTF_8)));
String response = httpclient.execute(httpPost).toString();
Log.i("response: ", response);
Log.i("JSON", jObject.toString());
} catch (ClientProtocolException e)
{
e.printStackTrace();
Log.e("Header","ClientProtocolException in callWebService(). "+ e.getMessage());
error = String.valueOf(e);
return false;
}
catch (IOException e)
{
e.printStackTrace();
Log.e("Header","IOException in callWebService(). " + e.getMessage());
error = String.valueOf(e);
return false;
}
return true;
}
protected void onPostExecute(Boolean valid)
{
progressDialog.dismiss();
Log.d("RESULT", String.valueOf(valid));
if(valid){
//Customzize toast here.
new DoPost(mContext,_username, _password, _code, _remarks, _date, _province, _infotype,_competitor,_brands, _segments).execute();
}else{
//Customzize toast here.
}
}
I think I've found out what's going on. Your scope is wrong. currently your code is running in AsyncTask, not Activity! That's why you cannot use getAssets, getLayoutInflater, findViewById, getBaseContext. Create your AsyncTask in your xxxActivity. And use Your xxxActivity.this.findViewById, and so on.