Cant authenticate my ACS token - android

Ive been trying to send messages to a azure service bus queue from android for a while and i just cant get it to work. This is the code i use for getting the ACS SWT:
private void getTokenFromACS() throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://servicebusnamespace-sb.accesscontrol.windows.net/WRAPv0.9/");
List<NameValuePair> parameters = new ArrayList<NameValuePair>(3);
parameters.add(new BasicNameValuePair("wrap_name", "name"));
parameters.add(new BasicNameValuePair("wrap_password", "password associated with the name"));
parameters.add(new BasicNameValuePair("wrap_scope", "Realm url"));
httppost.setEntity(new UrlEncodedFormEntity(parameters));
BasicHttpResponse httpResponse = null;
httpResponse = (BasicHttpResponse)httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String[] tokenVariables = URLDecoder.decode(reader.readLine()).split("&wrap_access_token_expires_in=");
authorizationToken = tokenVariables[0];
}
This works fine, i get a string that has the wrap_access_token, issuer, audience, expiresOn and HMACSHA256.
What i try to do after that is to send a message with this token like this:
HttpClient requestClient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://servicebusnamespace.servicebus.windows.net/queuename/messages");
post.addHeader("Authorization", "WRAP access_token=\""+authorizationToken+"\"");
Item item = new Item();
Date date = new Date();
item.setDate(date);
item.setId(1);
item.setRoadName("roadname");
item.setSpeed(60.0);
item.setLat(12.12);
item.setLng(12.12);
String json = new GsonBuilder().create().toJson(item, Item.class);
post.setEntity(new ByteArrayEntity(json.getBytes("UTF8")));
HttpResponse httpResponse = requestClient.execute(post);
This always result in my Token not being authenticated, i get the error message saying my token doesnt containt a signature or that it doesnt have the audience set. What could be wrong?
Note that this is on android =)
Thanks in advance!

Seems like you are missing some code. Your authorizationToken is currently something like this: "wrap_access_token=net.windows.servicebus.action%3dLis..."
The only thing you want is the part after the equal-sign.
I think this will do:
String[] tokenVariables = URLDecoder.decode(reader.readLine()).split("&wrap_access_token_expires_in=")[0].split("=");
authorizationToken = tokenVariables[1];

Related

How to Send the Viewstate String, asp page values Via Httppost

I have a code written in python which send's in the viewstate and the formvalues in this way
send('_VIEWSTATE=%2FwEPDwULLTE0MDM4Mz.........%2BhFiTeLDMyk...................&_EVENTVALIDATION=%2FwEWA....I%2.................mtK6HmOBny%2............NHcX5PO4r9oSpA&TextBox1='+payload+'&Button1=click\r\n')
where the dots stand for the rest of the string. Now i want to send this by httppost from android. I'm not able to understand how to translate the above code to httppost, i tried making the __VIEWSTATE,__EVENTVALIDATION as key's and the string's as value but that did not work. How can i send it ?? how do i send the above string as it is via httppost.
Do this:
private static final String DATA = "_VIEWSTATE=%2FwEPDwULLTE0MDM4Mz.........";
public String send() {
String result = null;
try {
HttpPost request = new HttpPost(new URI("<your POST uri>"));
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("data", DATA));
request.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BasicResponseHandler handler = new BasicResponseHandler();
result = handler.handleResponse(response);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Call the send() method from a background Thread.

What is wrong with this POST request with json on android?

I'm trying to perform a POST request to a server that wants the Content-Type set to application/json with name and email as some keys. Currently, I'm getting a 406 error, which I'm assuming is working on the server side, but android can't handle the response. How can I tweak the code to get a 200 response?
HttpClient client = new DefaultHttpClient();
HttpEntity entity;
try{
JSONObject j = new JSONObject();
j.put("name" , myName);
j.put("email", myEmail);
HttpPost post = new HttpPost(targetURL);
post.setHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(j.toString(), HTTP.UTF_8);
se.setContentType("application/json");
post.setEntity(se);
HttpResponse response = client.execute(post);
entity = response.getEntity();
Log.d("response", response.getStatusLine().toString());
} catch(Exception e){Log.e("exception", e.toString());}
Does that look about right? Do I need one of those response handlers when creating the HttpClient?
This works for me with json-2.0.jar
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), MyApplication.HTTP_TIMEOUT); //Timeout Limit
HttpResponse response;
ArrayList<appResults> arrayList = new ArrayList<appResults>();
String resul;
try{
HttpGet get = new HttpGet(urls[0]);
response = client.execute(get);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
resul = convertStreamToString(in);
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<appResults>>() {}.getType();
arrayList = gson.fromJson(resul, listType);
in.close();
of course in asynctask or thread.
But 406... it seems that your format on your webserver and your app are not consistent...

What is the best way to send a name value pair to a server?

I've been trying this for the best part of two weeks now, and I am really stuck. Initially I had created a simple ObjectOutputStream client - server program - with the client being the Android app, but it does not work (it reads the connection but not the object).
So now I am confused as to what other approaches I might be able to take to carry out this simple task? Can anyone Help?
have you tried URLConnection using post method? :)
Or get method like:
String yourURL = "www.yourwebserver.com?value1=one&value2=two";
URL url = new URL(yourURL);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
response = in.readLine();
you can try JSON stirng to send data. We have a lot of stuff available on how to work with JSON and also there are many api's. JSONSimple is the one I can suggest. Its really easy.
why don't you try this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
You can use this to post an Entity to server:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
postRequest.setEntity(entity);
try {
HttpResponse response = httpClient.execute(postRequest
);
String jsonString = EntityUtils.toString(response
.getEntity());
Log.v(ProgramConstants.TAG, "after uploading file "
+ jsonString);
return jsonString;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
An Entity can be name value pair:
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("key1", value1));
nvps.add(new BasicNameValuePair("key2", value2));
Entity entity=new UrlEncodedFormEntity(nvps, HTTP.UTF_8)
Or you can send an entity with bytearray.
Bitmap bitmapOrg=getBitmapResource();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
entity.addPart("file", new ByteArrayBody(data, "image/jpeg",
"file"));
If you want to post json to server:
Please check out this link How do I send JSon as BODY In a POST request to server from an Android application?
For serializing and deserializing java object, I recommend https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson
Really hope it can help you see an overview of sending data to server

passing an array of string using json

JSONObject jsonObj = new JSONObject();
jsonObj.put("email", email);
jsonObj.put("password", password);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost("http://api.readfa.st/session");
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);`
Currently I am working in an android project where i need to pass an array user[email], user[password] to a web page using json...please if any one can help me width this asap..Thank you!
I'm not sure what you mean. But I guess you need something like this:
JSONArray jsonArray = new JSONArray(listOfUsers);
String jsonRepresentationForListOfUsers = jsonArray.toString();
You can look here for further documentation.
http://developer.android.com/reference/org/json/JSONArray.html

Android HTTPRequest Cycle

I am trying to send JSON to my server and retrieve a JSON in return as a result.
Like sending in username and password and getting back token and other content.
This is what i am doing for the HTTP Request for sending. How do i now retrieve back the content in the same request ?
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://192.168.1.5/temp/test.php");
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("Name", jsonStr));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse res = client.execute(request);
String[] status_String=res.getStatusLine().toString().trim().split(" ");
//String hd=res.getFirstHeader("result").toString();
//System.out.println("Res=" + res);
Log.e("tag", ""+res.toString());
if(status_String[1].equals("200")){
isDataSent=true;
Let me add more in vvieux's answer:
res.getEntity().getContent()
will return you InputStream.
String returnData = EntityUtils.toString(res.getEntity());
You can use the HttpEntity
res.getEntity().getContent()

Categories

Resources