I want to integrate paypal in my web application. I am using RESTEasy API for restful requests. I want to know that how to integrate paypal in my application. I have dowonloaded paypal java sdk from their web site but right now I have no good applicaion which will help me to integrate paypal in my app. Can anybody suggest any site which shows step by step inegration of paypal in website or simple to understand ?
Paypal offers a few examples and even a wizard that generates you some code.
After the previous links gone offline start with this small tutorial: https://developer.paypal.com/docs/checkout/integrate/#
We have to follow the below step for configuring paypal in java web application.Here i have shown the configuration for Paypal to Paypal and CreditCard to Paypal payment.
1.create one sandbox account.
2.create web application.
3.Integrate the following struts2 action with your code.If you want to use with any other then just take methods and use directly.
public class PaypalAction extends ActionSupport implements SessionAware {
private static final long serialVersionUID = 1L;
private String resultString;
private String token;
#SuppressWarnings("rawtypes")
private Map finalMap = new HashMap();
public void paypalPay() {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
Integer payPercent = 10;
Map result = new HashMap();
String data1 = "";
try {
data1 = URLEncoder.encode("USER", "UTF-8") + "="+ URLEncoder.encode("Sandbox UserName","UTF-8");
data1 += "&" + URLEncoder.encode("PWD", "UTF-8") + "="+ URLEncoder.encode("Sandbox Password", "UTF-8");
data1 += "&" + URLEncoder.encode("SIGNATURE", "UTF-8") + "="+ URLEncoder.encode("Sandbox Signature","UTF-8");
data1 += "&" + URLEncoder.encode("METHOD", "UTF-8") + "="+ URLEncoder.encode("SetExpressCheckout", "UTF-8");
data1 += "&" + URLEncoder.encode("RETURNURL", "UTF-8") + "=" + URLEncoder.encode(request.getRequestURL().toString().replaceAll(request.getServletPath(), "") + "/successPage","UTF-8");
data1 += "&" + URLEncoder.encode("CANCELURL", "UTF-8") + "="+ URLEncoder.encode(request.getRequestURL().toString().replaceAll(request.getServletPath(), "") + "/failurePage", "UTF-8");
data1 += "&" + URLEncoder.encode("VERSION", "UTF-8") + "="+ URLEncoder.encode("104.0", "UTF-8");
data1 += "&" + URLEncoder.encode("AMT", "UTF-8")+ "=" + URLEncoder.encode("10", "UTF-8");
data1 += "&" + URLEncoder.encode("CURRENCYCODE", "UTF-8") + "=" + URLEncoder.encode("USD", "UTF-8");
data1 += "&" + URLEncoder.encode("L_NAME0", "UTF-8") + "=" + URLEncoder.encode("Sample Test", "UTF-8");
data1 += "&" + URLEncoder.encode("L_AMT0", "UTF-8") + "=" + URLEncoder.encode("10", "UTF-8");
data1 += "&" + URLEncoder.encode("CUSTOM", "UTF-8") + "="+ URLEncoder.encode("Thank You For business","UTF-8");
data1 += "&" + URLEncoder.encode("DESC", "UTF-8") + "=" + URLEncoder.encode("Product Details", "UTF-8");
data1 += "&" + URLEncoder.encode("NOSHIPPING", "UTF-8") + "="+ URLEncoder.encode("1", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
result = post(data1);
Iterator<?> iter = result.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mEntry = (Map.Entry) iter.next();
}
if(result!=null){
token = (String) result.get("TOKEN");
String url = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express"+ "-" + "checkout&token=" + (String) result.get("TOKEN");
try {
response.sendRedirect(url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String successPage() {
HttpServletRequest request = ServletActionContext.getRequest();
String payerID = request.getParameter("PayerID");
String token=request.getParameter("token");
doPaypalPayment(payerID,token);
return "success";
}
public String failurePage()
{
return "failurePage";
}
public void doPaypalPayment(String payerID, String token2) {
Map result = new HashMap();
String data = "";
try {
data1 = URLEncoder.encode("USER", "UTF-8") + "="+ URLEncoder.encode("Sandbox UserName","UTF-8");
data1 += "&" + URLEncoder.encode("PWD", "UTF-8") + "="+ URLEncoder.encode("Sandbox Password", "UTF-8");
data1 += "&" + URLEncoder.encode("SIGNATURE", "UTF-8") + "="+ URLEncoder.encode("Sandbox Signature","UTF-8");
data += "&" + URLEncoder.encode("METHOD", "UTF-8") + "="+ URLEncoder.encode("DoExpressCheckoutPayment", "UTF-8");
data += "&" + URLEncoder.encode("PAYERID", "UTF-8") + "="+ URLEncoder.encode(payerID, "UTF-8");
data += "&" + URLEncoder.encode("PAYMENTACTION", "UTF-8") + "="+ URLEncoder.encode("Sale", "UTF-8");
data += "&" + URLEncoder.encode("TOKEN", "UTF-8") + "="+ URLEncoder.encode(token2, "UTF-8");
data += "&" + URLEncoder.encode("AMT", "UTF-8") + "="+ URLEncoder.encode("10", "UTF-8");
data += "&" + URLEncoder.encode("VERSION", "UTF-8") + "="+ URLEncoder.encode("104.0", "UTF-8");
data += "&" + URLEncoder.encode("CURRENCYCODE", "UTF-8") + "="+ URLEncoder.encode("USD", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
result = post(data);
}
public void deformatNVP()
{
try
{
String delims = "[&]";
String equals = "[=]";
String[] tokens = this.resultString.split(delims);
for(int i = 0; i < tokens.length; i++)
{
String[] newTokens = tokens[i].split(equals);
this.finalMap.put(URLDecoder.decode(newTokens[0], "UTF-8"), URLDecoder.decode(newTokens[1], "UTF-8"));
}
} catch (Exception e) {
System.out.println(e.toString());
}
//return finalMap;
}
public Map post(String data)
{
try
{
//Connect to the url
URL url = new URL("https://api-3t.sandbox.paypal.com/nvp");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//Post the data
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
this.resultString = rd.readLine();
deformatNVP();
wr.close();
rd.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return finalMap;
}
#Override
public void setSession(Map<String, Object> arg0) {
// TODO Auto-generated method stub
}
public void doPaypalPaymentWithCreditCard() {
try
{
//Load the caller service
//Create a new map to hold the result
Map result = new HashMap();
// Construct data request string
String data1 = URLEncoder.encode("USER", "UTF-8") + "="+ URLEncoder.encode("Sandbox UserName","UTF-8");
data1 += "&" + URLEncoder.encode("PWD", "UTF-8") + "="+ URLEncoder.encode("Sandbox Password", "UTF-8");
data1 += "&" + URLEncoder.encode("SIGNATURE", "UTF-8") + "="+ URLEncoder.encode("Sandbox Signature","UTF-8"); data += "&" + URLEncoder.encode("METHOD", "UTF-8") + "=" + URLEncoder.encode("DoDirectPayment", "UTF-8");
data += "&" + URLEncoder.encode("AMT", "UTF-8") + "=" + URLEncoder.encode("20.10", "UTF-8");
data += "&" + URLEncoder.encode("VERSION", "UTF-8") + "=" + URLEncoder.encode("80.0", "UTF-8");
data += "&" + URLEncoder.encode("IPADDRESS", "UTF-8") + "=" + URLEncoder.encode("192.168.1.0", "UTF-8");
data += "&" + URLEncoder.encode("PAYMENTACTION", "UTF-8") + "=" + URLEncoder.encode("Sale", "UTF-8");
data += "&" + URLEncoder.encode("CREDITCARDTYPE", "UTF-8") + "=" + URLEncoder.encode("Visa", "UTF-8");
data += "&" + URLEncoder.encode("ACCT", "UTF-8") + "=" + URLEncoder.encode("4532513511140817", "UTF-8");
data += "&" + URLEncoder.encode("EXPDATE", "UTF-8") + "=" + URLEncoder.encode("102014", "UTF-8");
data += "&" + URLEncoder.encode("CVV2", "UTF-8") + "=" + URLEncoder.encode("123", "UTF-8");
data += "&" + URLEncoder.encode("FIRSTNAME", "UTF-8") + "=" + URLEncoder.encode("Jason", "UTF-8");
data += "&" + URLEncoder.encode("LASTNAME", "UTF-8") + "=" + URLEncoder.encode("Michels", "UTF-8");
data += "&" + URLEncoder.encode("STREET", "UTF-8") + "=" + URLEncoder.encode("123", "UTF-8");
data += "&" + URLEncoder.encode("CITY", "UTF-8") + "=" + URLEncoder.encode("Papillion", "UTF-8");
data += "&" + URLEncoder.encode("STATE", "UTF-8") + "=" + URLEncoder.encode("NE", "UTF-8");
data += "&" + URLEncoder.encode("ZIP", "UTF-8") + "=" + URLEncoder.encode("68046", "UTF-8");
data += "&" + URLEncoder.encode("COUNTRYCODE", "UTF-8") + "=" + URLEncoder.encode("US", "UTF-8");
result = post(data);
//This will iterate through the entire response map
Iterator iter = result.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mEntry = (Map.Entry) iter.next();
System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
}
//Now that you have a response check to see if it is a success
String ack = "" + result.get("ACK");
if("Success".equals(ack))
{
System.out.println("Congratulations your transaction was a success");
}
else
{
System.out.println("There was an error with your request.");
}
}
catch (Exception e)
{
System.out.println(e.toString());
}
}//end of main function
}
This is working fine for me.Hope it will help to those who want to configure payment through paypal.
Related
I am trying to create a RestAPI request to fetch details of a records with a filter 'START_WITH'. But every request I send is getting rejected with the error '401 Unauthorized. Invalid Signature'. But if I don't add the filter and only send the normal request, It gives correct response back.
My code for generating signature is:
public String generateOauthHeader(
String method, UserFields userFields, String baseUrl, String offset, String limit) {
long timestamp = new Date().getTime() / 1000;
String nonce = getAlphaNumericString();
ArrayList<String> parameters = new ArrayList<>();
parameters.add(
ApplicationConstants.CONSUMER_KEY
+ ApplicationConstants.EQUAL
+ userFields.getConsumerKey());
parameters.add(ApplicationConstants.NONCE + ApplicationConstants.EQUAL + nonce);
parameters.add(
ApplicationConstants.SIGNATURE_METHOD_KEY
+ ApplicationConstants.EQUAL
+ ApplicationConstants.SIGNATURE_METHOD_VAL);
parameters.add(ApplicationConstants.TIMESTAMP + ApplicationConstants.EQUAL + timestamp);
parameters.add(
ApplicationConstants.OAUTH_TOKEN + ApplicationConstants.EQUAL + userFields.getTokenId());
parameters.add(
ApplicationConstants.VERSION_KEY
+ ApplicationConstants.EQUAL
+ ApplicationConstants.VERSION_VAL);
if (offset != null) {
parameters.add(ApplicationConstants.OFFSET + ApplicationConstants.EQUAL + offset);
}
if (limit != null) {
parameters.add(ApplicationConstants.LIMIT_CLAUSE + ApplicationConstants.EQUAL + limit);
}
parameters.add("q" + ApplicationConstants.EQUAL + "companyname START_WITH COMP1234");
Collections.sort(parameters);
StringBuffer parametersList = new StringBuffer();
for (int i = 0; i < parameters.size(); i++) {
parametersList.append(((i > 0) ? ApplicationConstants.AMPERSAND : "") + parameters.get(i));
}
String signature = null;
try {
String signatureString =
method
+ ApplicationConstants.AMPERSAND
+ URLEncoder.encode(baseUrl, StandardCharsets.UTF_8)
+ ApplicationConstants.AMPERSAND
+ URLEncoder.encode(parametersList.toString(), StandardCharsets.UTF_8);
SecretKeySpec signingKey =
new SecretKeySpec(
(userFields.getConsumerSecret()
+ ApplicationConstants.AMPERSAND
+ userFields.getTokenSecret())
.getBytes(),
ApplicationConstants.HMACSHA256);
Mac m = Mac.getInstance(ApplicationConstants.HMACSHA256);
m.init(signingKey);
m.update(signatureString.getBytes());
byte[] res = m.doFinal();
signature = Base64Coder.encodeLines(res);
} catch (Exception e) {
e.printStackTrace();
}
return ApplicationConstants.OAUTH
+ ApplicationConstants.REALM
+ ApplicationConstants.EQUAL_START_QUOTES
+ userFields.getAccountId()
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.CONSUMER_KEY
+ ApplicationConstants.EQUAL_START_QUOTES
+ userFields.getConsumerKey()
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.OAUTH_TOKEN
+ ApplicationConstants.EQUAL_START_QUOTES
+ userFields.getTokenId()
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.SIGNATURE_METHOD_KEY
+ ApplicationConstants.EQUAL_START_QUOTES
+ ApplicationConstants.SIGNATURE_METHOD_VAL
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.TIMESTAMP
+ ApplicationConstants.EQUAL_START_QUOTES
+ timestamp
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.NONCE
+ ApplicationConstants.EQUAL_START_QUOTES
+ nonce
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.VERSION_KEY
+ ApplicationConstants.EQUAL_START_QUOTES
+ ApplicationConstants.VERSION_VAL
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.SIGNATURE
+ ApplicationConstants.EQUAL_START_QUOTES
+ URLEncoder.encode(signature, StandardCharsets.UTF_8)
+ ApplicationConstants.QUOTES;
}
Url generated without filter: https ://1212112-sb1.suitetalk.api.netsuite.com/services/rest/record/v1/customer/
Url generated with filter: https ://1212112-sb1.suitetalk.api.netsuite.com/services/rest/record/v1/customer?q="companyName START_WITH COMP1234"
I am writing a bot to auto purchase items on a website (zalando).
Everything goes well from login to adding items to shopping cart but at the very end it doesn't work anyomore. It sends this error:
{ "edge_error": "halt", "ref_id": "18.57c51102.1663765843.299fc0e", "wait": 60, "feedback": { "email": true, "url": "", "recaptcha": { "enabled": false, "type": 0, "sitekey": "" } }}
I think it has something to do with their protection or just me missing a header or cookie or a delay... I honestly have no clue anymore
This is the code I use in the end (to checkout and generate a paypal link (post response)):
public void makePostJsonRequest(WebDriver driver, String eTag, String checkoutID)
{
retrieveCookiesMap(driver);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost postRequest = new HttpPost("https://www.zalando.be/api/checkout/buy-now");
postRequest.setHeader("authority", "www.zalando.be");
postRequest.setHeader("accept", "application/json");
postRequest.setHeader("accept-language", "en-US,en;q=0.9");
postRequest.setHeader("content-type", "application/json");
postRequest.setHeader("cookie", "language-preference=nl;" +
" Zalando-Client-Id=" + cookiesMap.get("Zalando-Client-Id") + ";" +
" ncx=f;" +
" _gcl_au=" + cookiesMap.get("_gcl_au") + ";" +
" sqt_cap=" + cookiesMap.get("sqt_cap") + ";" +
" _ga=" + cookiesMap.get("_ga") + ";" +
" _gid=" + cookiesMap.get("_gid") + ";" +
" bm_sz=" + cookiesMap.get("bm_sz") + ";" +
" ak_bms=" + cookiesMap.get("ak_bms") + ";" +
" _gat_zalga=1;" +
" mpulseinject=false;" +
" frsx=" + cookiesMap.get("frsx") + ";" +
" zsa=" + cookiesMap.get("zsa") + ";" +
" zsr=" + cookiesMap.get("zsr") + ";" +
" zsi=" + cookiesMap.get("zsi") + ";" +
" bm_sv=" + cookiesMap.get("bm_sv") + ";" +
" _abck=" + cookiesMap.get("_abck") + ";");
postRequest.setHeader("origin", "https://www.zalando.be");
postRequest.setHeader("referer", "https://www.zalando.be/checkout/confirm");
postRequest.setHeader("sec-ch-ua", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"");
postRequest.setHeader("sec-ch-ua-mobile", "?0");
postRequest.setHeader("sec-ch-ua-platform", "\"Linux\"");
postRequest.setHeader("sec-fetch-dest", "empty");
postRequest.setHeader("sec-fetch-mode", "cors");
postRequest.setHeader("sec-fetch-site", "same-origin");
postRequest.setHeader("user-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36");
postRequest.setHeader("x-xsrf-token", cookiesMap.get("frsx"));
postRequest.setHeader("x-zalando-checkout-app", "web");
postRequest.setHeader("x-zalando-footer-mode", "desktop");
postRequest.setHeader("x-zalando-header-mode", "desktop");
eTag = StringUtils.chop(eTag);
eTag += "\\";
String jsonString = "{\"checkoutId\":\"" + checkoutID + "\"," +
"\"eTag\":" + "\"\\" + eTag + "\"" + "\"" + "}";
System.out.println(jsonString);
StringEntity entity = new StringEntity(jsonString);
postRequest.setEntity(entity);
long startTime = System.currentTimeMillis();
HttpResponse response = httpClient.execute(postRequest);
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Time taken : "+elapsedTime+"ms");
InputStream is = response.getEntity().getContent();
Reader reader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
while (true) {
try {
String line = bufferedReader.readLine();
if (line != null) {
builder.append(line);
} else {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(builder.toString());
System.out.println("****************");
} catch (Exception ex) {
ex.printStackTrace();
}
}
This means that Akamai (the provider that zalando uses for bot protection), has detected and stopped your request because it detected you as a bot. To avoid this "stop" you MUST send a valid _abck cookie, generated by passing sensor data to the zalando akamai endpoint( you can find using chrome devtools and analyzing the requests )
I'm trying to take the JSON from BITTREX and parse it and present it to the screen in Android Studio. This works for me with test JSON I made myself plus other requests i have made using the same API. However, when i go to use the actual request I need i get the following error :
JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
This is the request used: https://bittrex.com/api/v1.1/public/getmarketsummaries
API Documentation
Here is the Code :
public class fetchData extends AsyncTask<Void,Void,Void> {
String data=""; //all json lines after loop
String dataParsed ="";
String singleParsed =""; //parsed attributes
#Override
protected Void doInBackground(Void... voids) {
//Background Thread i.e API request
try {
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries\n");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream(); //read data in from the connection
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //Buff reader to read the inputstream (otherwise we get ints)
String line ="";
//Loop that reads all lines and represents them to as a string
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
}
JSONArray myJsonArray = new JSONArray(data); //store json in a json array
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
//Single JSON object parsed
singleParsed = "Coin" + myJsonObject.get("MarketName") + "\n" +
"high" + myJsonObject.get("High") + "\n" +
"low" + myJsonObject.get("Low") + "\n" +
"volume" + myJsonObject.get("Volume") + "\n" +
"last" + myJsonObject.get("Last") + "\n" +
"basevolume" + myJsonObject.get("BaseVolume") + "\n" +
"time" + myJsonObject.get("Timestamp") + "\n" +
"bid" + myJsonObject.get("Bid") + "\n" +
"ask" + myJsonObject.get("Ask") + "\n" +
"openbuyorders" + myJsonObject.get("OpenBuyOrders") + "\n" +
"opensellorders" + myJsonObject.get("OpenSellOrders") + "\n" +
"prevday" + myJsonObject.get("PrevDay") + "\n" +
"created" + myJsonObject.get("Created") + "\n";
dataParsed = dataParsed + singleParsed + "\n";
}
}catch(MalformedURLException e ){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//UI thread
MainActivity.data.setText(this.dataParsed);
}
}
Any thoughts would be greatly appreciated. Thanks :)
**UPDATE - SOLVED **
I added the following line before the loop and it solved the issue.
//target the "result" Array of objects(BTC,LTC,ETH) and map them to a JsonArray for parsing
JSONArray myJsonArray = myJsonObj.getJSONArray("result");
The exception is perfectly valid. Your trying to convert json object into json array. Try below code
remove "\n" character at the end.
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries\n")
add below logs
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
}
Log.debug("api_response","api-response->"+data);
and try below code
if(data!= null){ // add this if condition too.
JSONObject jsonObj = new JSONObject(data);
JSONArray myJsonArray = jsonObj.getJSONArray("result"); ; //store json in a json array
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
The json data returned by the API is in the following format:
{
"success": true,
"message": "",
"result": [
{
},
{
}
]
}
So you need to get the whole data as JSONObject first, then from it you can extract the JSONArray with the "result" key.
The code is something like this:
// get the JSONObject from the data
JSONObject jsonObject = new JSONObject(data);
// then you get the array with result key
JSONArray myJsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < myJsonArray.length(); i++) {
// now you can process the item here.
}
UPDATE
The above code is working. The remaining problem is there is a typo in your key. You're using "Timestamp" but the existing key is "TimeStamp". Here is the working code:
public class FetchData extends AsyncTask<Void,Void,Void> {
String data=""; //all json lines after loop
String dataParsed ="";
String singleParsed =""; //parsed attributes
#Override
protected Void doInBackground(Void... voids) {
//Background Thread i.e API request
try {
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream(); //read data in from the connection
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //Buff reader to read the inputstream (otherwise we get ints)
String line ="";
//Loop that reads all lines and represents them to as a string
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
Log.d("DATA", "line = " + line);
}
Log.d("DATA", "construct data = " + data);
JSONObject jsonObject = new JSONObject(data);
JSONArray myJsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
//Single JSON object parsed
singleParsed = "Coin" + myJsonObject.get("MarketName") + "\n" +
"high" + myJsonObject.get("High") + "\n" +
"low" + myJsonObject.get("Low") + "\n" +
"volume" + myJsonObject.get("Volume") + "\n" +
"last" + myJsonObject.get("Last") + "\n" +
"basevolume" + myJsonObject.get("BaseVolume") + "\n" +
"time" + myJsonObject.get("TimeStamp") + "\n" +
"bid" + myJsonObject.get("Bid") + "\n" +
"ask" + myJsonObject.get("Ask") + "\n" +
"openbuyorders" + myJsonObject.get("OpenBuyOrders") + "\n" +
"opensellorders" + myJsonObject.get("OpenSellOrders") + "\n" +
"prevday" + myJsonObject.get("PrevDay") + "\n" +
"created" + myJsonObject.get("Created") + "\n";
dataParsed = dataParsed + singleParsed + "\n";
}
}catch(MalformedURLException e ){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//UI thread
//MainActivity.data.setText(this.dataParsed);
Log.d("DATA", "data = " + this.dataParsed);
}
}
I am using twitter home_timeline API for showing tweets.For first time I run this it works fine, but when I call it again (pull to load more), it doesn't responds. I am passing auth headers and in params I passed count, it doesn't worked too.
I don't know where am I stuck..
Here is code for pulling tweets:
if (auth != null && auth.token_type.equals("bearer")) {
HttpGet httpget = new HttpGet(TwitterStreamURL);
String oAuthConsumerKey = CONSUMER_KEY;
String oAuthConsumerSecret = CONSUMER_SECRET;
String oAuthAccessToken = HomeActivity.twitter_access_token;
String oAuthAccessTokenSecret = HomeActivity.twitter_access_token_secret;
String oAuthNonce = String.valueOf(System.currentTimeMillis());
String oAuthSignatureMethod = "HMAC-SHA1";
String oAuthTimestamp = time();
String oAuthVersion = "1.0";
String signatureBaseString1 = methods;
String signatureBaseString2 = TwitterStreamURL;
String signatureBaseString3Templ = "oauth_consumer_key=%s&oauth_nonce=%s&oauth_signature_method=%s&oauth_timestamp=%s&oauth_token=%s&oauth_version=%s";
String signatureBaseString3 = String.format(signatureBaseString3Templ,
oAuthConsumerKey,
oAuthNonce,
oAuthSignatureMethod,
oAuthTimestamp,
oAuthAccessToken,
oAuthVersion);
String signatureBaseStringTemplate = "%s&%s&%s";
try {
signatureBaseString = String.format(signatureBaseStringTemplate,
URLEncoder.encode(signatureBaseString1, "UTF-8"),
URLEncoder.encode(signatureBaseString2, "UTF-8"),
URLEncoder.encode(signatureBaseString3, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
compositeKey = URLEncoder.encode(oAuthConsumerSecret, "UTF-8") + "&" + URLEncoder.encode(oAuthAccessTokenSecret, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
String oAuthSignature = computeSignature(signatureBaseString, compositeKey);
oAuthSignatureEncoded = URLEncoder.encode(oAuthSignature, "UTF-8");
String authorizationHeaderValueTempl = "OAuth oauth_consumer_key=\"%s\", oauth_nonce=\"%s\", oauth_signature=\"%s\", oauth_signature_method=\"%s\", oauth_timestamp=\"%s\", oauth_token=\"%s\", oauth_version=\"%s\"";
String authorizationHeaderValue = String.format(authorizationHeaderValueTempl,
oAuthConsumerKey,
oAuthNonce,
oAuthSignatureEncoded,
oAuthSignatureMethod,
oAuthTimestamp,
oAuthAccessToken,
oAuthVersion);
} catch (Exception e) {
e.printStackTrace();
}
String vf = "oauth_consumer_key=" + oAuthConsumerKey + ",oauth_signature_method=" + oAuthSignatureMethod + ",oauth_timestamp=" + oAuthTimestamp + ",oauth_nonce=" + oAuthNonce + ",oauth_version=" + oAuthVersion + ",oauth_token=" + oAuthAccessToken + ",oauth_signature=" + oAuthSignatureEncoded + "";
httpget.setHeader("Authorization", "OAuth " + "oauth_consumer_key=" + oAuthConsumerKey + ",oauth_signature_method=" + oAuthSignatureMethod + ",oauth_timestamp=" + oAuthTimestamp + ",oauth_nonce=" + oAuthNonce + ",oauth_version=" + oAuthVersion + ",oauth_token=" + oAuthAccessToken + ",oauth_signature=" + oAuthSignatureEncoded + "");
httpget.setHeader("Content-Type", "application/json");
// update the results with the body of the response
checkTwitRes = true;
results = getResponseBody(httpget);
}
div {
color:#000;
font-weight:800
}
p {
color:red;
background:url("mypicture.png")
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
{ "gb": [
{
"omrid": "gis-n",
"status": 0,
"grupp": 1
},
{
"omrid": "gis-s",
"status": 0,
"grupp": 1
},
{
"omrid": "gis-c",
"status": 0,
"grupp": 1
},
{
"omrid": "gis-h",
"status": 0,
"grupp": 1
},
{
"omrid": "gis-g",
"status": 0,
"grupp": 1
},
{
"omrid": "hes",
"status": 0,
"grupp": 2
} ] }
This above is my JSON String (edited shorter because it became too long here).
I'm trying to find a way to be able to iterate each group and create a togglebutton with them.
So what I'm trying to do is create a togglebutton with the name stated in "omrid" with the on/off status of "status". The "grupp" is for future use eventually to sort the toggles into groups but not important now.
I have searched and searched about this and noone seems to have my specific JSON string composition and I'm a bit of a noob with JSON/Android SDK.
I would use JSONObject. THer is no difference where you run in on Android or PC.
String str = "{" +
" \"gb\": [" +
" {" +
" \"omrid\": \"gis-n\"," +
" \"status\": 0," +
" \"grupp\": 1" +
" }," +
" {" +
" \"omrid\": \"gis-s\"," +
" \"status\": 0," +
" \"grupp\": 1" +
" }," +
" {" +
" \"omrid\": \"gis-c\"," +
" \"status\": 0," +
" \"grupp\": 1" +
" }," +
" {" +
" \"omrid\": \"gis-h\"," +
" \"status\": 0," +
" \"grupp\": 1" +
" }," +
" {" +
" \"omrid\": \"gis-g\"," +
" \"status\": 0," +
" \"grupp\": 1" +
" }," +
" {" +
" \"omrid\": \"hes\"," +
" \"status\": 0," +
" \"grupp\": 2" +
" }" +
" ]" +
"}";
JSONObject jsonObject = new JSONObject(str);
JSONArray gb = jsonObject.getJSONArray("gb");
for (int j = 0; j < gb.length(); j++) {
JSONObject element = gb.getJSONObject(j);
int status = element.getInt("status");
int grupp = element.getInt("grupp");
String omrid = element.getString("omrid");
System.out.println("status=" + status + "; grupp=" + grupp + "; omrid=" + omrid);
//create togglebutton here
}
Output:
status=0; grupp=1; omrid=gis-n
status=0; grupp=1; omrid=gis-s
status=0; grupp=1; omrid=gis-c
status=0; grupp=1; omrid=gis-h
status=0; grupp=1; omrid=gis-g
status=0; grupp=2; omrid=hes
here's the code
JSONObject json = new JSONObject(String your_json_string);
JSONArray arr = json.getJSONArray("gb");
for(int i = 0;i<arr.length();i++)
{
JSONObject temp = arr.getJSONObject(i);
temp.getString("omrid");//use them as your needs
temp.getString("status");//use them as your needs
temp.getString("grupp");// use them as your needs
}
Hope it helps.
Use following code to iterate.
Make one class JSONParser as below.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
public class JSONParser {
public JSONParser() {
}
JSONObject jObj;
String json;
InputStream is = null;
public JSONObject getJsonFromUrl(String url) {
// TODO Auto-generated method stub
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println("Json String : " + json);
} catch (Exception e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
return jObj;
}
}
In your MainActivity use following to iterate.
JSONParser parser = new JSONParser();
JSONObject o = parser.getJsonFromUrl("yourjsonurl");
JSONArray array = o.getJSONArray("gb");
for (int i = 0; i < array.length(); i++){
JSONObject j = array.getJSONObject(i);
String omrid = j.getString("omrid");
String status= j.getString("status");
String grupp = j.getString("grupp");
}