Android retrieve return value from WCF - android

I have an Android app that posts to a web service via the code below and it all works fine. But the myContract method in the service returns a Boolean, true or false. How do I retrieve that value so I can tell my app to move on or not if false?
HttpPost request = new HttpPost(SERVICE_URI + "/myContract/someString");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Edit
Sorry about the edit, but using HttpResponse, and then logging or toasting response.toString() returns a string I don’t understand!
Update
Thanks Shereef,
But that seems like a bit too much information and code to do what I was trying to do. I have added some code below that works but I’m not sure if it’s right. The service will return a Boolean true or false as to whether or not the POST was successful, but I seem to be retrieving it as a string!
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject jsonResponse = new JSONObject(new String(buffer));
String ServiceResponse = jsonResponse.getString("putCommuniqueResult");
Log.d("WebInvoke", "Saving : " + ServiceResponse);
Is this ok? It works but I’m not sure if its right!
Cheers,
Mike.

private static String getDataFromXML(final String text) {
final String temp = new String(text).split("<")[2].split(">")[1];
final String temp2 = temp.replace("<", "<").replace(">", ">")
.replace("&", "&");
return temp2;
}
/**
* Connects to the web service and returns the pure string returned, NOTE:
* if the generated url is more than 1024 it automatically delegates to
* connectPOST
*
* #param hostName
* : the host name ex: google.com or IP ex:
* 127.0.0.1
* #param webService
* : web service name ex: TestWS
* #param classOrEndPoint
* : file or end point ex: CTest
* #param method
* : method being called ex: TestMethod
* #param parameters
* : Array of {String Key, String Value} ex: { { "Username",
* "admin" }, { "Password", "313233" } }
* #return the trimmed String received from the web service
*
* #author Shereef Marzouk - http://shereef.net
*
*
*/
public static String connectGET(final String hostNameOrIP,
final String webService, final String classOrEndPoint,
final String method, final String[][] parameters) {
String url = "http://" + hostNameOrIP + "/" + webService + "/"
+ classOrEndPoint + "/" + method;
String params = "";
if (null != parameters) {
for (final String[] strings : parameters) {
if (strings.length == 2) {
if (params.length() != 0) {
params += "&";
}
params += strings[0] + "=" + strings[1];
} else {
Log.e(Standards.TAG,
"The array 'parameters' has the wrong dimensions("
+ strings.length + ") in " + method + "("
+ parameters.toString() + ")");
}
}
}
url += "?" + params;
if (url.length() >= 1024) { // The URL will be truncated if it is more
// than 1024
return Communications.connectPOST(hostNameOrIP, webService,
classOrEndPoint, method, parameters);
}
final StringBuffer text = new StringBuffer();
HttpURLConnection conn = null;
InputStreamReader in = null;
BufferedReader buff = null;
try {
final URL page = new URL(url);
conn = (HttpURLConnection) page.openConnection();
conn.connect();
in = new InputStreamReader((InputStream) conn.getContent());
buff = new BufferedReader(in);
String line;
while (null != (line = buff.readLine()) && !"null".equals(line)) {
text.append(line + "\n");
}
} catch (final Exception e) {
Log.e(Standards.TAG,
"Exception while getting " + method + " from " + webService
+ "/" + classOrEndPoint + " with parameters: "
+ params + ", exception: " + e.toString()
+ ", cause: " + e.getCause() + ", message: "
+ e.getMessage());
Standards.stackTracePrint(e.getStackTrace(), method);
return null;
} finally {
if (null != buff) {
try {
buff.close();
} catch (final IOException e1) {
}
buff = null;
}
if (null != in) {
try {
in.close();
} catch (final IOException e1) {
}
in = null;
}
if (null != conn) {
conn.disconnect();
conn = null;
}
}
if (text.length() > 0 && Communications.checkText(text.toString())) {
final String temp = Communications.getDataFromXML(text.toString());
Log.i(Standards.TAG, "Success in " + method + "(" + params
+ ") = " + temp);
return temp;
}
Log.w(Standards.TAG, "Warning: " + method + "(" + params + "), text = "
+ text.toString());
return null;
}
let's say this url makes your service shows it's output
http://google.com/wcfsvc/service.svc/showuserdata/11949
public boolean isWSTrue() {
String data = connectGET("google.com",
"wcfsvc", "service.svc",
"showuserdata/11949", null);
if(null != data && data.length() >0)
return data.toLowerCase().contains("true");
throw new Exception("failed to get webservice data");
}
Note: that within this case you do not actually need to parse the JSON or XML if only checking for boolean then you know if you found true it's true if found anything else it's false.
if you need to get data using XML or JSON you can refer to this answer https://stackoverflow.com/a/3812146/435706

Related

Android: Generate Oauth1 Signature in Volley Request

I am trying to add Oauth1 Authorization in my android app using volley
in the postman when i add the details like oauth_consumer_key, oauth_consumer_secret , token_key token_secret like the picture below
it generate a header like below picture and response received successfully.
Postman generated header
Authorization:OAuth oauth_consumer_key="4e77abaec9b6fcda9kjgkjgh44c2e1",oauth_token="2da9439r34104293b1gfhse2feaffca9a1",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1482470443",oauth_nonce="cCbH5b",oauth_version="1.0",oauth_signature="A1QPwTATVF4x3cN0%2FN46CZrtSKw%3D"
Problem
I googled a lot to create oauth signature like postmasn created to attach volley ServerConnectionChannel but failed.
oauth_signature="A1QPwTATVF4x3cN0%2FN46CZrtSKw%3D"
Current code
public void doSendJsonRequest(final ERequest ERequest) {
requestMethod = String.valueOf(ERequest.method);
requestUrl = String.valueOf(ERequest.mReqUrl);
if(requestMethod.equals(Request.Method.GET)){
requestMethod = "GET";
}else if(requestMethod.equals(Request.Method.POST)){
requestMethod = "POST";
}else if(requestMethod.equals(Request.Method.PUT)){
requestMethod = "PUT";
}else if(requestMethod.equals(Request.Method.DELETE)){
requestMethod = "DELETE";
}
Long tsLong = System.currentTimeMillis()/1000;
final String ts = tsLong.toString();
final String kk = requestMethod+"&" + encode(requestUrl)+"&";
final String kk = encode("GET"+"&"
+ requestUrl+"&"
+ OAUTH_CONSUMER_KEY + "=\"4e77abaec9b6fcda9b11e89a9744c2e1\"&"
+OAUTH_NONCE + "=\"" + getNonce()+ "\"&"
+OAUTH_SIGNATURE_METHOD + "=\""+OAUTH_SIGNATURE_METHOD_VALUE+"\"&"
+OAUTH_TIMESTAMP + "=\"" + ts + "\"&"
+OAUTH_TOKEN +"=\"2da943934104293b167fe2feaffca9a1\"");
RequestQueue queue = VolleyUtils.getRequestQueue();
try {
JSONObject jsonObject = ERequest.jsonObject;
EJsonRequest myReq = new EJsonRequest(ERequest.method, ERequest.mReqUrl, jsonObject, createReqSuccessListener(ERequest), createReqErrorListener(ERequest)) {
public Map < String, String > getHeaders() throws AuthFailureError {
// Long tsLong = System.currentTimeMillis()/1000;
// String ts = tsLong.toString();
String strHmacSha1 = "";
String oauthStr = "";
strHmacSha1 = generateSignature(kk, oAuthConsumerSecret, oAuthTokenSecret);
strHmacSha1 = toSHA1(strHmacSha1.getBytes());
Log.e("SHA !",strHmacSha1);
oauthStr ="OAuth "+ OAUTH_CONSUMER_KEY + "=\"4e77abaec9b6fcda9b11e89a9744c2e1\","
+OAUTH_TOKEN +"=\"2da943934104293b167fe2feaffca9a1\","
+OAUTH_SIGNATURE_METHOD + "=\""+OAUTH_SIGNATURE_METHOD_VALUE+"\","
+OAUTH_TIMESTAMP + "=\"" + ts + "\","
+OAUTH_NONCE + "=\"" + getNonce()+ "\","
+OAUTH_VERSION + "=\"" + OAUTH_VERSION_VALUE + "\","
+OAUTH_SIGNATURE + "=\"" + strHmacSha1+ "\"";
Log.e("VALUE OF OAuth str",oauthStr);
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Authorization",oauthStr);
// params.put("Authorization",getConsumer().toString());
return params;
}
};
myReq.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 4,
BABTAIN_MAX_RETRIES,
BABTAIN_BACKOFF_MULT));
myReq.setHeader("Cache-Control", "no-cache");
//myReq.setHeader("Content-Type", "application/json");
queue.add(myReq);
} catch (Exception e) {
e.printStackTrace();
}
private String generateSignature(String signatueBaseStr, String oAuthConsumerSecret, String oAuthTokenSecret) {
byte[] byteHMAC = null;
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec spec;
if (null == oAuthTokenSecret) {
String signingKey = encode(oAuthConsumerSecret) + '&';
spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
} else {
String signingKey = encode(oAuthConsumerSecret) + '&' + encode(oAuthTokenSecret);
spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
}
mac.init(spec);
byteHMAC = mac.doFinal(signatueBaseStr.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
String base64 = Base64.encodeToString(byteHMAC, Base64.DEFAULT);
return base64.trim();
}
private String toSHA1(byte[] convertme) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
}
catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
return byteArrayToHexString(md.digest(convertme));
}
private String byteArrayToHexString(byte[] b) {
String result = "";
for (int i=0; i < b.length; i++)
result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
return result;
}
this code create a signature like :oauth_signature="42a611860e29e893a435b555e7a9559a704f4e94" and it failed to get autherization.
getting error like : BasicNetwork.performRequest: Unexpected response code 401 for url
?How to generate oauth_signature like postman provided using volley..
?how can i improve this code ?Is any libraries or default function to do that
?How we add oauth1 signature in volley..
Please Help.. Thank you
I just found a github example for generating signature corresponding to nonce in Oauth1 and successfully integrate into my project
here is the link : https://github.com/rameshvoltella/WoocommerceAndroidOAuth1

Getting the Response code 401 message in twitter api request

The below code is getting response code 401.please help anyone to get search tweets from twitter api.I am using http urlconnection instead of httprequest.I need to get response tweets using jsonobject
HttpURLConnection urlConnection=null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twitterlayout);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
twitter_consumer_key= "";
twitter_consumer_secret="";
oauth_token = "";
oauth_token_secret = "";
q="India";
String get_or_post = "GET";
// This is the signature method used for all Twitter API calls
String oauth_signature_method = "HMAC-SHA1";
// generate any fairly random alphanumeric string as the "nonce". Nonce = Number used ONCE.
String uuid_string = UUID.randomUUID().toString();
uuid_string = uuid_string.replaceAll("-", "");
String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here
// get the timestamp
Calendar tempcal = Calendar.getInstance();
long ts = tempcal.getTimeInMillis();// get current time in milliseconds
String oauth_timestamp = (new Long(ts/1000)).toString(); // then divide by 1000 to get seconds
// assemble the proper parameter string, which must be in alphabetical order, using your consumer key
String parameter_string = "lang=en&oauth_consumer_key=" + twitter_consumer_key + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method +
"&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + URLEncoder.encode(oauth_token) + "&oauth_version=1.0&q=" + URLEncoder.encode(q) + "&result_type=mixed";`enter code here`
enter code here
Log.d("parameter_string=",parameter_string);
twitter_endpoint = "https://api.twitter.com/1.1/users/search.json";
twitter_url="https://api.twitter.com/1.1/users/search.json?q=india";
String signature_base_string = get_or_post + "&"+ URLEncoder.encode(twitter_endpoint) + "&" + URLEncoder.encode(parameter_string);
String oauth_signature = "";
try {
oauth_signature = computeSignature(signature_base_string, twitter_consumer_secret + "&");
}
catch (GeneralSecurityException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String authorization_header_string = "OAuth oauth_consumer_key=\"" + twitter_consumer_key + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp +
"\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + URLEncoder.encode(oauth_signature) + "\",oauth_token=\"" + URLEncoder.encode(oauth_token) + "\"";
Log.d("Header String",authorization_header_string);
URL url = null;
try
{
Log.d("Url",twitter_url);
url = new URL(twitter_url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Host", "api.twitter.com");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
urlConnection.setRequestProperty("Authorization",authorization_header_string);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setUseCaches(false);
int responseCode = urlConnection.getResponseCode();
Log.d("Response Code :", String.valueOf(responseCode));
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String responsedata = null;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject topLevel = new JSONObject(jsonCallbackToJson(builder.toString()));
Log.d("Toplevel", builder.toString());
}
catch (MalformedURLException e) {
e.printStackTrace();
Log.i("URL-ERROR:",e.toString());
}
catch (IOException | JSONException e)
{
e.printStackTrace();
Log.i("IO-ERROR:", e.toString());
}
}
401 means you have broke something with authentication
However, don't reinvent the wheel.
You can use TwitterCore Kit that handle authentication and is easy to use tool for your needs. It provides a TwitterApiClient for making authenticated Twitter API requests.

Apache HTTP Client Android Exception on Execute only for LG G3 6.0

I've taken over an android app that takes pictures and attaches them to jobs for a larger software system at a company's home base- it has worked fine until recently.
It seems that only on LG G3 phones that have upgraded to Android 6.0 there is an exception in this prodecure:
public static String frapiGetRequest(String transaction, ArrayList<Content> parameters) {
StringBuilder builder = new StringBuilder();
DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost(HOST,PORT,SCHEME);
String url = SCHEME + "://" + HOST + "/" + transaction;
if (parameters != null && parameters.size() > 0) {
url += "?" + buildParameterString(parameters);
}
Utilities.bLog(TAG, "Making FrapiRequest -- " + url);
try {
HttpGet getRequest = new HttpGet(url);
client.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials(USERNAME, PASSWORD));
/**Exception Occurs Here**/
HttpResponse response = client.execute(getRequest);
StatusLine statusLine = response.getStatusLine();
int statusCode = -1;
statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Utilities.bLog(TAG,"Frapi Request Succeeded");
}
else {
Utilities.bLog(TAG, "Frapi Request Failed: " + url);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Utilities.eLog(e);
} catch (IOException e) {
e.printStackTrace();
Utilities.eLog(e);
} catch (Exception e) {
e.printStackTrace();
Utilities.eLog(e);
}
return builder.toString();
}
The stack trace
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at org.apache.http.impl.auth.DigestScheme.isGbaScheme(DigestScheme.java:210)
at org.apache.http.impl.auth.DigestScheme.processChallenge(DigestScheme.java:176)
at org.apache.http.impl.client.DefaultRequestDirector.processChallenges(DefaultRequestDirector.java:1097)
at org.apache.http.impl.client.DefaultRequestDirector.handleResponse(DefaultRequestDirector.java:980)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:490)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
at com.rossware.sd_quickpics.Utilities.frapiGetRequest(Utilities.java:111)
at com.rossware.sd_quickpics.Business.authenticate(Business.java:83)
at com.rossware.sd_quickpics.MainActivity$AuthenticateAsyncTask.doInBackground(MainActivity.java:320)
at com.rossware.sd_quickpics.MainActivity$AuthenticateAsyncTask.doInBackground(MainActivity.java:307)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
This hasn't been reported on any other phone.. I would use HttpURLConnection But it doesn't support Digest Authentication (which is currently what our frapi server is using)
I'm just not sure if there's any way to continue using the authentication mechanism we have or if I have to implement a different protocol in frapi (hopefully without breaking all of our existing applications..) or if there is another way to bypass this issue for the folks with these phones? This issue is pretty restricted (one client who has about 10 phones, not the end of the world, but definitely a major issue for them)
Is there anything in android that I can do to resolve this kind of problem for the affected users? Does it seem like the code is incorrect?
It is possible to use DigestAuth with HttpUrlConnection:
private InputStream connect(String urlStr, String username, String password) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) new URL(urlStr).openConnection();
connection.setDoInput(true);
connection.setRequestMethod("GET");
try {
return connection.getInputStream();
} catch(Exception e) {
if (connection.getResponseCode() == 401) {
String header = connection.getHeaderField("WWW-Authenticate");
String uri = new URL(urlStr).getFile();
String nonce = Tools.match(header, "nonce=\"([A-F0-9]+)\"");
String realm = match(header, "realm=\"(.*?)\"");
String qop = match(header, "qop=\"(.*?)\"");
String algorithm = match(header, "algorithm=(.*?),");
String cnonce = generateCNonce();
String ha1 = username + ":" + realm + ":" + password;
String ha1String = md5digestHex(ha1);
String ha2 = "GET" + ":" + uri;
String ha2String = md5digestHex(ha2);
int nc = 1;
String response = ha1String + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2String;
String responseString = md5digestHex(response);
String authorization =
"Digest username=\"" + username + "\"" +
", realm=\"" + realm + "\"" +
", nonce=\"" + nonce + "\"" +
", uri=\"" + uri + "\"" +
", qop=\"" + qop + "\"" +
", nc=\"" + nc + "\"" +
", cnonce=\"" + cnonce + "\"" +
", response=\"" + responseString + "\"" +
", algorithm=\"" + algorithm + "\"";
HttpURLConnection digestAuthConnection = prepareConnection(urlStr);
digestAuthConnection.setRequestMethod("GET");
digestAuthConnection.setRequestProperty("Authorization", authorization);
return processResponse(digestAuthConnection);
} else throw e;
}
}
public static String match(String s, String patternString, boolean strict) {
if (!isEmpty(s) && !isEmpty(patternString)) {
Pattern pattern = Pattern.compile(patternString);
if (pattern != null) {
Matcher matcher = pattern.matcher(s);
if (matcher != null && matcher.find() && (matcher.groupCount() == 1 || !strict)) {
return matcher.group(1);
}
}
}
return null;
}
public static String match(String s, String patternString) {
return match(s, patternString, true);
}
public static byte[] md5Digist(String s) {
try {
MessageDigest md5 = MessageDigest.getInstance("md5");
md5.update(s.getBytes());
return md5.digest();
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static String digest2HexString(byte[] digest) {
String digestString="";
int low, hi;
for (int i = 0; i < digest.length; i++) {
low = (digest[i] & 0x0f ) ;
hi = ((digest[i] & 0xf0) >> 4);
digestString += Integer.toHexString(hi);
digestString += Integer.toHexString(low);
}
return digestString;
}
public static String md5digestHex(String s) {
return digest2HexString(md5Digist(s));
}
public static String generateCNonce() {
String s = "";
for (int i = 0; i < 8; i++) {
s += Integer.toHexString(new Random().nextInt(16));
}
return s;
}
I ran into a similar issue today and just started using HttpClient for Android
Added dependency compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1' to build.gradle.
Replace new DefaultHttpClient() with HttpClientBuilder.create().build()
There are probably some other minor refactors you might need to make in other portions of the code, but that should be pretty straight forward.

Android upload video to Asynctask

i wrote code witch can upload video in vimeo.i use scribe library.code working perfect.now i want to use Asynctask to upload video.i have no idea how i can use aAsynctask at the moment
this is a upload video source
upload_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
accessToken = checkToken(vimeoAPIURL, accessToken, service);
if (accessToken == null) {
System.out.println("Error");
}
UploadVideoinVimeo();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
public void UploadVideoinVimeo() throws Exception {
request = new OAuthRequest(Verb.GET, vimeoAPIURL);
request.addQuerystringParameter("method",
"vimeo.videos.upload.getQuota");
signAndSendToVimeo(request, "getQuota", true);
// Get Ticket
request = new OAuthRequest(Verb.GET, vimeoAPIURL);
request.addQuerystringParameter("method",
"vimeo.videos.upload.getTicket");
request.addQuerystringParameter("upload_method", "streaming");
response = signAndSendToVimeo(request, "getTicket", true);
// Get Endpoint and ticket ID
System.out.println(newline + newline
+ "We're sending the video for upload!");
Document doc = readXML(response.getBody());
Element ticketElement = (Element) doc.getDocumentElement()
.getElementsByTagName("ticket").item(0);
String endpoint = ticketElement.getAttribute("endpoint");
String ticketId = ticketElement.getAttribute("id");
// Setup File
File testUp = new File(mVideoFilename);
boolean sendVideo = sendVideo(endpoint, testUp);
if (!sendVideo) {
throw new Exception("Didn't successfully send the video.");
}
// Complete Upload
request = new OAuthRequest(Verb.PUT, vimeoAPIURL);
request.addQuerystringParameter("method",
"vimeo.videos.upload.complete");
request.addQuerystringParameter("filename", testUp.getName());
request.addQuerystringParameter("ticket_id", ticketId);
Response completeResponse = signAndSendToVimeo(request, "complete",
true);
// Set video info
setVimeoVideoInfo(completeResponse, service, accessToken, vimeoAPIURL);
}
private static boolean sendVideo(String endpoint, File file)
throws FileNotFoundException, IOException {
// Setup File
long contentLength = file.length();
String contentLengthString = Long.toString(contentLength);
int size = (int) file.length();
FileInputStream is = new FileInputStream(file);
byte[] bytesPortion = new byte[size];
int maxAttempts = 5; // This is the maximum attempts that will be given
// to resend data if the vimeo server doesn't
// have the right number of bytes for the given
// portion of the video
long lastByteOnServer = 0;
boolean first = false;
while (is.read(bytesPortion, 0, size) != -1) {
lastByteOnServer = prepareAndSendByteChunk(endpoint,
contentLengthString, lastByteOnServer, bytesPortion, first,
0, maxAttempts);
if (lastByteOnServer == -1) {
return false;
}
first = true;
// getProgressBar().setValue(NumberHelper.getPercentFromTotal(byteNumber,
// getFileSize()));
}
return true;
}
/**
* Prepares the given bytes to be sent to Vimeo
*
* #param endpoint
* #param contentLengthString
* #param lastByteOnServer
* #param byteChunk
* #param first
* #param attempt
* #param maxAttempts
* #return number of bytes currently on the server
* #throws FileNotFoundException
* #throws IOException
*/
private static long prepareAndSendByteChunk(String endpoint,
String contentLengthString, long lastByteOnServer,
byte[] byteChunk, boolean first, int attempt, int maxAttempts)
throws FileNotFoundException, IOException {
if (attempt > maxAttempts) {
return -1;
} else if (attempt > 0) {
System.out.println("Attempt number " + attempt + " for video "
+ "Test Video");
}
long totalBytesShouldBeOnServer = lastByteOnServer + byteChunk.length;
String contentRange = lastByteOnServer + "-"
+ totalBytesShouldBeOnServer;
long bytesOnServer = sendVideoBytes(endpoint, contentLengthString,
"video/mp4", contentRange, byteChunk, first);
if (bytesOnServer != totalBytesShouldBeOnServer) {
System.err.println(bytesOnServer + " (bytesOnServer)" + " != "
+ totalBytesShouldBeOnServer
+ " (totalBytesShouldBeOnServer)");
long remainingBytes = totalBytesShouldBeOnServer - bytesOnServer;
int beginning = (int) (byteChunk.length - remainingBytes);
int ending = (int) byteChunk.length;
byte[] newByteChunk = Arrays.copyOfRange(byteChunk, beginning,
ending);
return prepareAndSendByteChunk(endpoint, contentLengthString,
bytesOnServer, newByteChunk, first, attempt + 1,
maxAttempts);
} else {
return bytesOnServer;
}
}
/**
* Sends the given bytes to the given endpoint
*
* #return the last byte on the server (from verifyUpload(endpoint))
*/
private static long sendVideoBytes(String endpoint, String contentLength,
String fileType, String contentRange, byte[] fileBytes,
boolean addContentRange) throws FileNotFoundException, IOException {
OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
request.addHeader("Content-Range", "bytes" + contentRange);
// request.addHeader("Content-Length", contentLength);
request.addHeader("Content-Type", fileType);
if (addContentRange) {
request.addHeader("Content-Range", "bytes " + contentRange);
}
request.addPayload(fileBytes);
Response response = signAndSendToVimeo(request, "sendVideo on "
+ "Test title", false);
if (response.getCode() != 200 && !response.isSuccessful()) {
return -1;
}
return verifyUpload(endpoint);
}
/**
* Verifies the upload and returns whether it's successful
*
* #param endpoint
* to verify upload to
* #return the last byte on the server
*/
private static long verifyUpload(String endpoint) {
// Verify the upload
OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
request.addHeader("Content-Length", "0");
request.addHeader("Content-Range", "bytes */*");
Response response = signAndSendToVimeo(request, "verifyUpload to "
+ endpoint, true);
if (response.getCode() != 308 || !response.isSuccessful()) {
return -1;
}
String range = response.getHeader("Range");
// range = "bytes=0-10485759"
return Long.parseLong(range.substring(range.lastIndexOf("-") + 1)) + 1;
// The + 1 at the end is because Vimeo gives you 0-whatever byte where 0
// = the first byte
}
/**
* Checks the token to make sure it's still valid. If not, it pops up a
* dialog asking the user to authenticate.
*/
private static Token checkToken(String vimeoAPIURL, Token vimeoToken,
OAuthService vimeoService) {
if (vimeoToken == null) {
// vimeoToken = getNewToken(vimeoService);
} else {
OAuthRequest request = new OAuthRequest(Verb.GET, vimeoAPIURL);
request.addQuerystringParameter("method",
"vimeo.oauth.checkAccessToken");
Response response = signAndSendToVimeo(request, "checkAccessToken",
true);
if (response.isSuccessful()
&& (response.getCode() != 200
|| response.getBody().contains("<err code=\"302\"") || response
.getBody().contains("<err code=\"401\""))) {
// vimeoToken = getNewToken(vimeoService);
}
}
return vimeoToken;
}
/**
* Gets authorization URL, pops up a dialog asking the user to authenticate
* with the url and the user returns the authorization code
*
* #param service
* #return
*/
/**
* Sets the video's meta-data
*/
private static void setVimeoVideoInfo(Response response,
OAuthService service, Token token, String vimeoAPIURL) {
OAuthRequest request;
Document doc = readXML(response.getBody());
org.w3c.dom.Element ticketElement = (org.w3c.dom.Element) doc
.getDocumentElement().getElementsByTagName("ticket").item(0);
String vimeoVideoId = ticketElement.getAttribute("video_id");
GlobalClasses.VimeoId = vimeoVideoId;
// Set title, description, category, tags, private
// Set Title
request = new OAuthRequest(Verb.POST, vimeoAPIURL);
request.addQuerystringParameter("method", "vimeo.videos.setTitle");
request.addQuerystringParameter("title", "1322");
request.addQuerystringParameter("video_id", vimeoVideoId);
signAndSendToVimeo(request, "setTitle", true);
// Set description
request = new OAuthRequest(Verb.POST, vimeoAPIURL);
request.addQuerystringParameter("method", "vimeo.videos.setDescription");
request.addQuerystringParameter("description",
"This is my test description");
request.addQuerystringParameter("video_id", GlobalClasses.VimeoId);
signAndSendToVimeo(request, "setDescription", true);
List<String> videoTags = new ArrayList<String>();
videoTags.add("test1");
videoTags.add("");
videoTags.add("test3");
videoTags.add("test4");
videoTags.add("test 5");
videoTags.add("test-6");
videoTags
.add("test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7 test 7");
// Create tags string
String tags = "";
for (String tag : videoTags) {
tags += tag + ", ";
}
tags.replace(", , ", ", "); // if by chance there are empty tags.
// Set Tags
request = new OAuthRequest(Verb.POST, vimeoAPIURL);
request.addQuerystringParameter("method", "vimeo.videos.addTags");
request.addQuerystringParameter("tags", tags);
request.addQuerystringParameter("video_id", vimeoVideoId);
signAndSendToVimeo(request, "addTags", true);
// Set Privacy
request = new OAuthRequest(Verb.POST, vimeoAPIURL);
request.addQuerystringParameter("method", "vimeo.videos.setPrivacy");
request.addQuerystringParameter("privacy", (true) ? "nobody"
: "anybody");
request.addQuerystringParameter("video_id", vimeoVideoId);
signAndSendToVimeo(request, "setPrivacy", true);
}
/**
* Signs the request and sends it. Returns the response.
*
* #param request
* #return response
*/
public static Response signAndSendToVimeo(OAuthRequest request,
String description, boolean printBody)
throws org.scribe.exceptions.OAuthException {
System.out
.println(newline
+ newline
+ "Signing "
+ description
+ " request:"
+ ((printBody && !request.getBodyContents().isEmpty()) ? newline
+ "\tBody Contents:"
+ request.getBodyContents()
: "")
+ ((!request.getHeaders().isEmpty()) ? newline
+ "\tHeaders: " + request.getHeaders() : ""));
service.signRequest(accessToken, request);
printRequest(request, description);
Response response = request.send();
printResponse(response, description, printBody);
return response;
}
/**
* Prints the given description, and the headers, verb, and complete URL of
* the request.
*
* #param request
* #param description
*/
private static void printRequest(OAuthRequest request, String description) {
System.out.println();
System.out.println(description + " >>> Request");
System.out.println("Headers: " + request.getHeaders());
System.out.println("Verb: " + request.getVerb());
System.out.println("Complete URL: " + request.getCompleteUrl());
}
/**
* Prints the given description, and the code, headers, and body of the
* given response
*
* #param response
* #param description
*/
private static void printResponse(Response response, String description,
boolean printBody) {
System.out.println();
System.out.println(description + " >>> Response");
System.out.println("Code: " + response.getCode());
System.out.println("Headers: " + response.getHeaders());
if (printBody) {
System.out.println("Body: " + response.getBody());
}
}
/**
* This method will Read the XML and act accordingly
*
* #param xmlString
* - the XML String
* #return the list of elements within the XML
*/
private static Document readXML(String xmlString) {
Document doc = null;
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource xmlStream = new InputSource();
xmlStream.setCharacterStream(new StringReader(xmlString));
doc = dBuilder.parse(xmlStream);
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
how i can rewrite this code to use Asynctask? if anyone knows solution help me
Create a class that extends AsyncTask and put your async method in doInBackground(...) like this:
private class VideoUpload extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//your upload code here
return "Executed";
}
#Override
protected void onPostExecute(String result) {}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
Then call your asyncTask like this:
new VideoUpload().execute();

Every second HttpsUrlConnection request of my static method fails on Android

I'm having a big issue with a static HTTPS connection method. Every second request fails and HttpsUrlConnection.getResponseCode() returns -1. So every second call works well, returning data as expected.
It's the method of a static class I'm using in different corners of my application. I would guess there is anything I don't clean up correctly when the method returns the first time and that whatever causes a problem might get destroyed through a second call of the method. But I'm having a hard time finding any clues.
I'm currently using this class to talk to hosts with invalid SSL certificates. Not going to use this in the final version of the app, but right now I need to save money. ;)
public static String makeInvalidHTTPSRequest(String url, String[] postVars, String userName, String userPass, Context ctx) throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {
StringBuffer sb = new StringBuffer();
String serverAuth = null;
String serverAuthBase64 = null;
StringBuffer urlParameters = new StringBuffer();
InputStream rcvdInputStream = null;
if (checkNetworkAvailability(ctx) == false) {
GeneralMethods.writeLog("Network unavailable", 1, GeneralMethods.class);
return null;
}
SSLContext sc = null;
sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { new KTPTrustManager() }, new SecureRandom());
GeneralMethods.writeLog("makeInvalidHTTPSRequest-> " + url + ", " + userName + ", " + userPass, 0, GeneralMethods.class);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new KTPHostnameVerifier());
HttpsURLConnection con = null;
con = (HttpsURLConnection) new URL(url).openConnection();
if (userName != null) {
serverAuth = userName + ":" + userPass;
serverAuthBase64 = KTPBase64.encode(serverAuth.getBytes());
}
try {
String[] tmpPair = null;
con.setRequestMethod("POST");
if (serverAuthBase64 != null)
con.setRequestProperty("Authorization", "Basic " + serverAuthBase64);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (postVars != null) {
for (int i = 0; i < postVars.length; i++) {
tmpPair = postVars[i].toString().split("=");
if (i > 0)
urlParameters.append("&" + tmpPair[0] + "=" + URLEncoder.encode(tmpPair[1], "UTF-8"));
else
urlParameters.append(tmpPair[0] + "=" + URLEncoder.encode(tmpPair[1], "UTF-8"));
}
con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.toString().getBytes().length));
}
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream wr = new DataOutputStream (con.getOutputStream());
if (postVars != null)
wr.writeBytes (urlParameters.toString());
wr.flush();
wr.close();
if (con.getResponseCode() == 200) {
globalRetries = 0;
rcvdInputStream = con.getInputStream();
}
else if (con.getResponseCode() == 401) {
con.disconnect();
GeneralMethods.writeLog("error 401", 2, GeneralMethods.class);
con = null;
// SEND CONNECTION PROBLEM-INTENT
return null;
}
else {
GeneralMethods.writeLog("error - connection response code " + con.getResponseCode() + ": " + con.getResponseMessage() + " (length: "+ con.getContentLength() +")\n\n", 1, GeneralMethods.class);
con.disconnect();
con = null;
// SEND CONNECTION PROBLEM-INTENT
return null;
}
BufferedReader br = new BufferedReader(new InputStreamReader(rcvdInputStream), 8192 );
String line;
while ( ( line = br.readLine() ) != null ) {
sb.append(line);
}
con.disconnect();
con = null;
}
catch(Exception e) {
handleException(e, 2, GeneralMethods.class);
}
GeneralMethods.writeLog("makeInvalidHTTPSRequest: Response is \"" + sb.toString() + "\"\n\n", 0, GeneralMethods.class);
if(con != null) {
con.disconnect();
con = null;
}
if (sb.toString().trim() == "")
return null;
else
return sb.toString();
}
Thanks a lot for your help!
Best regards
S.
This might be of help: HttpsURLConnection and intermittent connections

Categories

Resources