Webview Send Post Json - java

I have String Json:
String data = "param:"+"{\"dataFile\": \n" +
"{\"user\": \"asdasdasd\", \n" +
"\"pwd\":\"vasdadsda\", \"email\": \"vasdasdasd#gg.com\" \n" +
"}\n" +
"}";
Then try to send post to API with webview JSON like this:
myWebView.postUrl("url.com", data.getBytes());
from API the json process with "param" key then get the value, but the json get from API is null, any clue ?

I post my data like this. You may also try with this.
String postData = null;
try {
postData = "email=" + URLEncoder.encode(MyApp.getSharedPrefString(StaticData.EMAIL), "UTF-8") + "&password=" + URLEncoder.encode(MyApp.getSharedPrefString(StaticData.PASSWORD), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
webview.postUrl("url.com",postData.getBytes());

Related

Generating an SAS Token in Java to download a file in an Azure Data Storage container

Trying to generate an SAS Token to access certain files in a Storage Account. I'm using the methods listed here:
https://learn.microsoft.com/en-us/rest/api/eventhub/generate-sas-token
Now, the problem I have is I cannot, for the life of me, make the sasToken string work. If I generate the token via the Portal (Shared Access Signature in the Storage Account), I can access those files via a URL with the provided Token.
However I have yet to be able to generate an SAS token programmatically via Java using the methods I linked above. I think my problem is the StringToSign that is being encrypted. I've been following this example when constructing the string to encrypt:
https://learn.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas
All my efforts have resulted in either:
<AuthenticationErrorDetail>Signature fields not well formed.</AuthenticationErrorDetail>
or
<AuthenticationErrorDetail>Signature did not match. String to sign used was <insert string details here>
Looking at the Portal generated sasToken that works for me:
?sv=2017-11-09&ss=f&srt=o&sp=r&se=2018-12-06T22:15:20Z&st=2018-12-06T14:15:20Z&spr=https&sig=%2Bi1TWv5D80U%2BoaIeoBh1wjaO1p4xVFx4nRZt%2FzwiszY%3D
It seems I need a String like so:
String stringToSign = accountName + "\n" +
"r\n" +
"f\n" +
"o\n" +
URLEncoder.encode(start, "UTF-8") + "\n" +
URLEncoder.encode(expiry, "UTF-8") + "\n" +
"\n" +
"https\n" +
azureApiVersion;
Where accountName is the storage account name from Azure, and start/expiry are the start and expiry strings (ie- 2018-12-06T22:15:20Z) and azureApiVersion is "2017-11-09".
I then try to return the token after constructing the string like so:
String signature = getHMAC256(key, stringToSign);
sasToken = "sv=" + azureApiVersion +
"&ss=f" +
"&srt=o" +
"&sp=r" +
"&se=" +URLEncoder.encode(expiry, "UTF-8") +
"&st=" + URLEncoder.encode(start, "UTF-8") +
"&spr=https" +
"&sig=" + URLEncoder.encode(signature, "UTF-8");
I've tried URL encoding and not URL encoding the the start/expiry dates as well, just in case that was messing things up. What am I missing?
Three points to fix
getHMAC256 method problem as mentioned by #Gaurav
Don't encode expiry and start in stringToSign or the signature won't match. Because the encoded part in url will be decoded by Azure Storage Service to calculate the expected signature.
In stringToSign, miss one \n after azureApiVersion.
Here's the complete sample.
public static void GetFileSAS(){
String accountName = "accountName";
String key = "accountKey";
String resourceUrl = "https://"+accountName+".file.core.windows.net/fileShare/fileName";
String start = "startTime";
String expiry = "expiry";
String azureApiVersion = "2017-11-09";
String stringToSign = accountName + "\n" +
"r\n" +
"f\n" +
"o\n" +
start + "\n" +
expiry + "\n" +
"\n" +
"https\n" +
azureApiVersion+"\n";
String signature = getHMAC256(key, stringToSign);
try{
String sasToken = "sv=" + azureApiVersion +
"&ss=f" +
"&srt=o" +
"&sp=r" +
"&se=" +URLEncoder.encode(expiry, "UTF-8") +
"&st=" + URLEncoder.encode(start, "UTF-8") +
"&spr=https" +
"&sig=" + URLEncoder.encode(signature, "UTF-8");
System.out.println(resourceUrl+"?"+sasToken);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private static String getHMAC256(String accountKey, String signStr) {
String signature = null;
try {
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(accountKey), "HmacSHA256");
Mac sha256HMAC = Mac.getInstance("HmacSHA256");
sha256HMAC.init(secretKey);
signature = Base64.getEncoder().encodeToString(sha256HMAC.doFinal(signStr.getBytes("UTF-8")));
} catch (Exception e) {
e.printStackTrace();
}
return signature;
}
I got a simpler method
SharedAccessAccountPolicy sharedAccessAccountPolicy = new SharedAccessAccountPolicy();
sharedAccessAccountPolicy.setPermissionsFromString("racwdlup");
long date = new Date().getTime();
long expiryDate = new Date(date + 8640000).getTime();
sharedAccessAccountPolicy.setSharedAccessStartTime(new Date(date));
sharedAccessAccountPolicy.setSharedAccessExpiryTime(new Date(expiryDate));
sharedAccessAccountPolicy.setResourceTypeFromString("sco");
sharedAccessAccountPolicy.setServiceFromString("bfqt");
String sasToken = "?" + storageAccount.generateSharedAccessSignature(sharedAccessAccountPolicy);
You can get the storage account like this:
private String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=<storage name>;AccountKey=<your key>;EndpointSuffix=core.windows.net";
storageAccount = CloudStorageAccount.parse(storageConnectionString);

Parsing Merriam Webster JSON data attributes wrapped in a double array?

I am attempting to get the definition of a word using the documentation from Merriam Webster's API - https://dictionaryapi.com/products/json#sec-2.def
The documentation shows the structure of the JSON response from the server, and I have been able to successfully parse the raw data into a just an array containing the "sense" object.
Screenshot of code and parsed data
My issue is being able to access the "sense" JSONObject, since I am currently in an array, I can't access the sense object. I have tried adding .getJSONArray(0) and .getJSONObject(0) after my code and both of those solutions did not work.
How can I continue parsing this JSON I currently have to the "dt" string?
JSONArray merriamResults = data.getJSONArray("Merriam")
.getJSONObject(0)
.getJSONArray("def")
.getJSONObject(0)
.getJSONArray("sseq")
.getJSONArray(0)
.getJSONArray(0);
Here.
String json = "{\"def\":[\n" +
" {\n" +
" \"sseq\":[\n" +
" [\n" +
" [\n" +
" \"sense\",\n" +
" {\n" +
" \"dt\":[[\"text\",\"{bc}a {a_link|backward} somersault especially\n" +
" in the air\"]]\n" +
" }\n" +
" ]\n" +
" ]\n" +
" ]\n" +
" }\n" +
"]}";
try {
JSONObject jsonObject = new JSONObject(json);
String dt = jsonObject.getJSONArray("def")
.getJSONObject(0)
.getJSONArray("sseq")
.getJSONArray(0)
.getJSONArray(0)
.getJSONObject(1)
.getJSONArray("dt")
.getJSONArray(0)
.getString(1);
Log.i("jsondata", dt);
} catch (JSONException e) {
e.printStackTrace();
}
my log:
12-02 21:38:12.316 14174-14174/com.example.pemba.sample I/jsondata: {bc}a {a_link|backward} somersault especially
in the air

how to send request payload in json data using post method

String pay= "["
+ "{"
+ "\"internalAssessmentResponseId\" : \"Mer\\/ccclsv__AC1B752E-D079-4BA9-AA4F-46E1F8DDC11F__3048\","
+ "\"responses\":["
+ "{"
+ "\"assessmentCreatedDate\":\"2016-11-25T11:35:54\","
+ "\"responseData\":[],"
+ "\"assessmentId\":\"943\","
+ "}"
+ "],"
+ "\"addtionalInformation\":[],"
+ "\"emailId\":\"lucky#me.com\","
+ "\"salesTeam\" :\"\","
+ "\"demographic\": {"
+ "},"
+ "\"repId\":\"AJMA-OG9OMQ\","
+ "\"assesseeId\":\"AGHA-2D0FVL\","
+ "\"assesseeType\":\"CONTACT\","
+ "\"typeOfResponse\":\"iPad\","
+ "\"userTimeZone\":\"a\""
+ "}"
+ "]";
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod("http://signature");
post.setRequestEntity(new StringRequestEntity(pay, "application/json", null));
httpclient.executeMethod(post);
String jsonResponse = post.getResponseBodyAsString();
jsonInsertRes = jsonResponse;
System.out.println("Response in create==>"+jsonResponse);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch
(IOException e)
{
e.printStackTrace();
}
return jsonString.toString();
}
I am getting wrong response like this
Can not construct instance of org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput, problem: abstract types can only be instantiated with additional type information
at [Source: org.apache.catalina.connector.CoyoteInputStream#11ff00b3; line: 1, column: 1]
You can try sending JSON string as a string form parameter
and then on server read the JSON string value and convert the string to a Java Object(say object of Message.java as for example).
Message msgFromJSON = new ObjectMapper().readValue(JSONString, Message.class);
I have tried few times and it worked fine.

URL in JSON object as POST request Android

Please help me to send a JSON object in POST HTTP request through HttpClient, in Android.
The problem I am facing is that the JSON object having the URL is replaced by forward slash ,i.e
originally it should have the following value in JSON object
{"product":
{"featured_src":"https:\/\/example.com\/wp-content\/uploads\/2015\/06\/sidney-compressed.jpg,
"short_description":"this is a test","title":"Raiders from the North"}
}
i tried many options to keep it in the above format. But it always comes as {"featured_src":
We assume this is your input
private final static String JSON_DATA = "{"
+ " \"product\": ["
+ " {"
+ " \"featured_src\": \"https:\\/\\/example.com\\/wp-content"
+ "\\/uploads\\/2015\\/06\\/sidney-compressed.jpg\","
+ " \"short_description\": \"this is a test\","
+ " \"title\" : \"Raiders from the North\""
+ " }"
+ " ]"
+ "}";
You could use replace to do the trick.
YOUR_STRING.replace("\\", "");
Finally your method would look like this, by passing your string as parameter
private static String jsonUrlCorrector(String json_data) {
json_data = json_data.replace("\\", "");
return json_data;
}
Here is the input:
{"product":[{"featured_src":"https:\/\/example.com\/wp-content\/uploads\/2015\/06\/sidney-compressed.jpg","short_description": "this is a test","title":"Raiders from the North"}]}
Here is the output
{"product":[{"featured_src":"https://example.com/wp-content/uploads/2015/06/sidney-compressed.jpg","short_description":"this is a test","title":"Raiders from the North"}]}

Google custom search engine android not accepting %20 or white space

EDIT 2
Found my error i was passing invalid an invalid parameter just remebered i was tryiong out stuff.
Sorry For the Trouble GUYS
I am using Google custom search engine for the first time and so far every thing is fine. However, when i try to send a query for an item which has a white space the search engine returns a bad request response eg
myUrl = (CustomSearchEngineURL + API_KEY + "&cx=" + cxKey + "&q="
+ q.replace(" ", "%20") + "&searchType=" + searchType
+ "&imgType=" + imgType + "&imgSize=" + imgSize + "&num=20&alt=json");
This returns this
com.google.api.client.http.HttpResponseException: 400 Bad Request
EDIT
i took the advice of 323go and tried encoding my q and this is how i implemented it
String encodedParms = null;
try {
encodedParms = URLEncoder.encode(q, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
myUrl = (CustomSearchEngineURL + API_KEY + "&cx=" + cxKey + "&q="
+ encodedParms + "&searchType=" + searchType + "&imgType="
+ imgType + "&imgSize=" + imgSize + "&num=20&alt=json");
Log.d(Tag, myUrl);
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request;
try {
request = httpRequestFactory.buildGetRequest(new GenericUrl(myUrl));
String response = streamToString(request.execute().getContent());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In my log i got this as the url
https://www.googleapis.com/customsearch/v1?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-w&cx=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&q=Sunway+Lagoon+Theme+Park&searchType=image&imgType=photo&imgSize=xxlarge&num=20&alt=json
i still got the same bad request error
please can anyone tell me what i am doing worng
Why dont you add "+" between words, I had same issue
With "word1 word2" - response 400 - Bad request
With "word1+word2" - response 2000 - Bad request

Categories