Url contain special charectors - blackberry

I am trying to establish a https connection but my URL contains some special characters, so creating the connection is throwing an Exception. How do I avoid this problem?

You can encode like this,
public class URLUTF8Encoder
{
final static String[] hex = {
"%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07",
"%08", "%09", "%0a", "%0b", "%0c", "%0d", "%0e", "%0f",
"%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
"%18", "%19", "%1a", "%1b", "%1c", "%1d", "%1e", "%1f",
"%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27",
"%28", "%29", "%2a", "%2b", "%2c", "%2d", "%2e", "%2f",
"%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37",
"%38", "%39", "%3a", "%3b", "%3c", "%3d", "%3e", "%3f",
"%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47",
"%48", "%49", "%4a", "%4b", "%4c", "%4d", "%4e", "%4f",
"%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57",
"%58", "%59", "%5a", "%5b", "%5c", "%5d", "%5e", "%5f",
"%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67",
"%68", "%69", "%6a", "%6b", "%6c", "%6d", "%6e", "%6f",
"%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77",
"%78", "%79", "%7a", "%7b", "%7c", "%7d", "%7e", "%7f",
"%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87",
"%88", "%89", "%8a", "%8b", "%8c", "%8d", "%8e", "%8f",
"%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97",
"%98", "%99", "%9a", "%9b", "%9c", "%9d", "%9e", "%9f",
"%a0", "%a1", "%a2", "%a3", "%a4", "%a5", "%a6", "%a7",
"%a8", "%a9", "%aa", "%ab", "%ac", "%ad", "%ae", "%af",
"%b0", "%b1", "%b2", "%b3", "%b4", "%b5", "%b6", "%b7",
"%b8", "%b9", "%ba", "%bb", "%bc", "%bd", "%be", "%bf",
"%c0", "%c1", "%c2", "%c3", "%c4", "%c5", "%c6", "%c7",
"%c8", "%c9", "%ca", "%cb", "%cc", "%cd", "%ce", "%cf",
"%d0", "%d1", "%d2", "%d3", "%d4", "%d5", "%d6", "%d7",
"%d8", "%d9", "%da", "%db", "%dc", "%dd", "%de", "%df",
"%e0", "%e1", "%e2", "%e3", "%e4", "%e5", "%e6", "%e7",
"%e8", "%e9", "%ea", "%eb", "%ec", "%ed", "%ee", "%ef",
"%f0", "%f1", "%f2", "%f3", "%f4", "%f5", "%f6", "%f7",
"%f8", "%f9", "%fa", "%fb", "%fc", "%fd", "%fe", "%ff"
};
public static String encode(String s)
{
StringBuffer sbuf = new StringBuffer();
int len = s.length();
for (int i = 0; i < len; i++) {
int ch = s.charAt(i);
if ('A' <= ch && ch <= 'Z') { // 'A'..'Z'
sbuf.append((char)ch);
} else if ('a' <= ch && ch <= 'z') { // 'a'..'z'
sbuf.append((char)ch);
} else if ('0' <= ch && ch <= '9') { // '0'..'9'
sbuf.append((char)ch);
} else if (ch == ' ') { // space
sbuf.append('+');
} else if (ch == '-' || ch == '_' // unreserved
|| ch == '.' || ch == '!'
|| ch == '~' || ch == '*'
|| ch == '\'' || ch == '('
|| ch == ')') {
sbuf.append((char)ch);
} else if (ch <= 0x007f) { // other ASCII
sbuf.append(hex[ch]);
} else if (ch <= 0x07FF) { // non-ASCII <= 0x7FF
sbuf.append(hex[0xc0 | (ch >> 6)]);
sbuf.append(hex[0x80 | (ch & 0x3F)]);
} else { // 0x7FF < ch <= 0xFFFF
sbuf.append(hex[0xe0 | (ch >> 12)]);
sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
sbuf.append(hex[0x80 | (ch & 0x3F)]);
}
}
return sbuf.toString();
}
}
referenced By
HTTP://WWW.W3.ORG/INTERNATIONAL/URLUTF8ENCODER.JAVA

There are several solutions for this. Pick the one you like most.

Related

String Task Codeforces Problem - https://codeforces.com/problemset/problem/118/A

https://codeforces.com/problemset/problem/118/A
my code:
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string str;
cin >> str;
for(int i=0; i<sizeof(str); i++)
{
if(str[i] >= 'A' && str[i] <= 'Z')
str[i]+=32;
{
if(str[i] >= 'a' && str[i] <= 'z' && str[i] != 'a' && str[i] != 'e' && str[i] != 'i' && str[i] != 'o' && str[i] != 'u' && str[i] != 'A' && str[i] != 'E' && str[i] != 'I' && str[i] != 'O' && str[i] != 'U')
cout << "." << str[i];
}
}
return 0;
}
Where is the problem in this code because it gives wrong when I submit?
I am not seeing any problem, could anyone help me to detect?
In the question they have included 'y' as a vowel too. I changed some other stuff too (like, use i<str.size() not i<sizeof(str) ), try the following code it will get accepted :
int main()
{
string str;
cin >> str;
for(int i=0; i<str.size(); i++)
{
char temp;
temp = str[i];
if(temp >= 'A' && temp <= 'Z')
temp = tolower(temp);
if(temp != 'a' && temp != 'e' && temp != 'i' && temp != 'o' && temp != 'u' && temp != 'y')
cout << "." << temp;
}
return 0;
}

I dont understand this line of code (hexchar_to_int(str[i]) << 4) | hexchar_to_int(str[i+1])) . Can someone explains me

I reviewed these lines of codes which used to convert string to binary, but i cant understand what this
line of code is doing (hexchar_to_int(str[i]) << 4) | hexchar_to_int(str[i+1]), i am frustrated
with this bit manipulation here, 8 bit of unsigned int used and we shifted left to get the least 4
significant bits. But i don't know the purpose of doing so.
unsigned char hexchar_to_int(char const ch)
{
if (ch >= '0' && ch <= '9') return ch - '0';
if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
throw std::invalid_argument("Invalid hexadecimal character");
}
std::vector<unsigned char> hexstr_to_bytes(std::string_view str)
{
std::vector<unsigned char> result;
for (size_t i = 0; i < str.size(); i += 2)
{
result.push_back((hexchar_to_int(str[i]) << 4) | hexchar_to_int(str[i+1]));
}
return result;
}
<<4 is *2^4 or *16, shifting left, not right.
The | is a simple addition of the 2 hexa characters at their correct place.
See 0xab = 10*16 + 11 = 171

URLEncoding from Objc to Swift 3

We are using following URL encoding in Objective C now we are migrating to swift .what will be the equivalent encoding for below ObjC to swift 3.
- (NSString *) URLEncodedString {
NSMutableString * output = [NSMutableString string];
const unsigned char * source = (const unsigned char *)[self UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:#"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:#"%c", thisChar];
} else {
[output appendFormat:#"%%%02X", thisChar];
}
}
return output;
}
This code should generate exactly the same result as your Objective-C code.
(Should compile and work as expected in both Swift 3 and 4.)
extension String {
var urlEncoded: String {
var output = ""
for thisChar in self.utf8 {
switch thisChar {
case UInt8(ascii: " "):
output.append("+")
case UInt8(ascii: "."), UInt8(ascii: "-"), UInt8(ascii: "_"), UInt8(ascii: "~"),
UInt8(ascii: "a")...UInt8(ascii: "z"),
UInt8(ascii: "A")...UInt8(ascii: "Z"),
UInt8(ascii: "0")...UInt8(ascii: "9"):
output.append(Character(UnicodeScalar(UInt32(thisChar))!))
default:
output = output.appendingFormat("%%%02X", thisChar)
}
}
return output
}
}
print("https://www.google.es".urlEncoded) //->https%3A%2F%2Fwww.google.es
Some points:
You can iterate on each UTF-8 byte with for thisChar in self.utf8
To convert a string literal (actually a UnicodeScalar Literal) to a UInt8, you can use UInt8(ascii:)
You should better consider using addingPercentEncoding(withAllowedCharacters:) with proper CharacterSet and pre/post-processing
You can probably do it this way -
extension String{
func urlEncodedString() -> String {
var output = String()
let source: [UInt8] = Array(self.utf8)
let sourceLen: Int = source.count
for i in 0..<sourceLen {
let thisChar = source[i]
if thisChar == UInt8(ascii: " ") {
output += "+"
}
else if thisChar == UInt8(ascii: ".") || thisChar == UInt8(ascii: "-") || thisChar == UInt8(ascii: "_") || thisChar == UInt8(ascii: "~") || (thisChar >= UInt8(ascii: "a") && thisChar <= UInt8(ascii: "z")) || (thisChar >= UInt8(ascii: "A") && thisChar <= UInt8(ascii: "Z")) || (thisChar >= UInt8(ascii: "0") && thisChar <= UInt8(ascii: "9")) {
output += "\(Character(UnicodeScalar(UInt32(thisChar))!))"
}
else {
output += String(format: "%%%02X", thisChar)
}
}
return output
}
}
Just replace below code (Swift 3.1.1):
func urlEncodedString() -> String {
var output = String()
let source: [UInt8] = UInt8(utf8)
let sourceLen: Int = strlen(CChar(source))
for i in 0..<sourceLen {
let thisChar: UInt8 = source[i]
if thisChar == " " {
output += "+"
}
else if thisChar == "." || thisChar == "-" || thisChar == "_" || thisChar == "~" || (thisChar >= "a" && thisChar <= "z") || (thisChar >= "A" && thisChar <= "Z") || (thisChar >= "0" && thisChar <= "9") {
output += "\(thisChar)"
}
else {
output += String(format: "%%%02X", thisChar)
}
}
return output
}
Try this swift 3 compatible code. I've tested it in a playground and works fine.
extension String {
func urlEncodedString() -> String {
var output = ""
for thisChar in self.utf8 {
if thisChar == UInt8(ascii: " ") {
output += "+"
}
else if thisChar == UInt8(ascii: ".") ||
thisChar == UInt8(ascii: "-") ||
thisChar == UInt8(ascii: "_") ||
thisChar == UInt8(ascii: "~") ||
(thisChar >= UInt8(ascii: "a") && thisChar <= UInt8(ascii: "z")) ||
(thisChar >= UInt8(ascii: "A") && thisChar <= UInt8(ascii: "Z")) ||
(thisChar >= UInt8(ascii: "0") && thisChar <= UInt8(ascii: "9")) {
output += "\(Character(UnicodeScalar(UInt32(thisChar))!))"
}
else {
output += String(format: "%%%02X", thisChar)
}
}
return output
}
}
Example usage:
let url = "https://www.google.es".urlEncodedString()
print(url)

Objective C URL with Vertical pipes/bars

I am trying to have vertical pipes in the URL
Input String: http://testURL.com/Control?command=dispatch|HOME|ABC:User Name
-(NSString *)getURLEncodedString:(NSString *)stringvalue{
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[stringvalue UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ':' || thisChar == '/' || thisChar == '?' || thisChar == '=' || thisChar == '|' || thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:#"%c", thisChar];
} else {
[output appendFormat:#"%%%02X", thisChar];
}
}
return output;
}
Output String after calling above method: http://testURL.com/Control?command=dispatch|HOME|ABC:User%20Name
Now, if I pass the above encode string to [[NSURL URLWithString:encodedString];
I am getting Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0xae9d760 {NSUnderlyingError=0xaec8ed0 "bad URL", NSLocalizedDescription=bad URL}
Any input on this guys? I want the URL to look like the encodedString.
Thank you!
I really cannot see a reason to encode/escape your string manually... Any way, this will work just fine:
NSString *urlString = #"http://testURL.com/Control?command=dispatch|HOME|ABC:User Name";
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Which outputs:
http://testURL.com/Control?command=dispatch%7CHOME%7CABC:User%20Name
It seems that NSURL doesn't like vertical bars after all, which you didn't encode in your method and thus getting a bad URL code.

scanf and gets buffer

im having a problem with scanf and gets. and I kno that its bound to errors but I couldn't find any other way. This way, the name is printing out but It doesn't print out the first letter of it.
Here's my code:
#include <stdio.h>
float calculations(int age, float highBP, float lowBP);
char option;
int counter, age;
char temp_name[50];
float highBP, lowBP, riskF, optimalH = 120.0, optimalL = 80.0;
typedef struct {
char name[50]; /*which represents the patient’s name*/
int age; /*which represents the patient’s age*/
float highBP; /*highBP, which represents the patient’s high (systolic) blood pressure*/
float lowBP; /*lowBP, which represents the patient’s low (diastolic) blood pressure*/
float riskF; /*riskFactor, which represents the patient’s risk factor for stroke due to hypertension.*/
}patient;/*end structure patient*/
patient *pRecords[30];
void printMenu()
{
printf("\n---------------------------------------------------------\n");
printf("|\t(N)ew record\t(D)isplay db\t(U)pdate record\t|\n");
printf("|\t(L)oad disk\t(W)rite disk\t(E)mpty disk\t|\n");
printf("|\t(S)ort db\t(C)lear db\t(Q)uit \t\t|\n");
printf("---------------------------------------------------------\n");
printf("choose one:");
}/*end print menu*/
void enter()
{
if(counter == 30)
printf("database full.");
else{
printf("name: ");
while(getchar()=='\n');
gets(temp_name);
strcpy(pRecords[counter]->name , temp_name);
printf("age: "); scanf("%d", &age);
pRecords[counter]->age = age;
printf("highBP: "); scanf("%f", &highBP);
pRecords[counter]->highBP = highBP;
printf("lowBP: "); scanf("%f", &lowBP);
pRecords[counter]->lowBP = lowBP;
float temp = calculations(age, highBP,lowBP);
pRecords[counter]->riskF = temp;
/*printf("name: %s, age: %d, highbp:%.1f, lowBP:%.1f\n", pRecords[counter]->name,pRecords[counter]->age,pRecords[counter]->highBP,pRecords[counter]->lowBP);
printf("risk factor: %.1f\n", pRecords[counter]->riskF);*/
counter ++;
}
}/*end of void enter function*/
memallocate(int counter){
pRecords[counter] = (patient *)malloc (sizeof(patient));
}/*end memallocate function*/
void display()
{
printf("===============================\n");
int i;
for(i=0; i<counter; i++)
{
printf("name: %s\n", pRecords[i]->name);
printf("age: %d\n", pRecords[i]->age);
printf("bp: %.2f %.2f\n", pRecords[i]->highBP, pRecords[i]->lowBP);
printf("risk: %.2f\n\n", pRecords[i]->riskF);
}/*end of for loop*/
printf("========== %d records ==========", counter);
}/*end of display method*/
float calculations(int age, float highBP, float lowBP)
{ float risk;
if((highBP <= optimalH) && (lowBP <= optimalL))
{ risk = 0.0;
if(age >=50)
risk = 0.5;
}
else if(highBP <= optimalH && (lowBP>optimalL && lowBP <=(optimalL+10)))
{ risk= 1.0;
if(age >=50)
risk = 1.5;
}
else if ((highBP >optimalH && highBP <= (optimalH+10))&& lowBP <=optimalL)
{ risk= 1.0;
if(age >=50)
risk= 1.5;
}
else if((highBP > optimalH && highBP <=(optimalH+10)) && (lowBP >optimalL && lowBP <= (optimalL+10)))
{ risk= 2.0;
if(age >=50)
risk = 2.5;
}
else if(highBP < optimalH && (lowBP >(optimalL+11) && lowBP<(optimalL+20)))
{ risk = 3.0;
if(age >=50)
risk = 3.5;
}
else if((lowBP < optimalL) && (highBP >(optimalH+11) && highBP<(optimalH+20)))
{ risk = 3.0;
if(age >=50)
risk = 3.5;
}
else if((highBP>=(optimalH+11) && highBP <= (optimalH+20))&& (lowBP>=(optimalL+11) && lowBP<=(optimalL+20)))
{ risk = 4.0;
if(age >=50)
risk = 4.5;
}
else
{ risk = 5.0;
if(age >=50)
risk = 5.5;
}
return risk;
}/*end of calculation function*/
main()
{
printMenu();
char option=getchar();
while(option != 'q' || option != 'Q'){
if(option == 'N' || option == 'n')
{
memallocate(counter);
enter();
printMenu();
}
if (option == 'L' || option == 'l')
{
printMenu();
}
if(option == 'S' || option == 's')
{
printMenu();
}
if(option == 'D' || option == 'd')
{
display();
printMenu();
}
if(option == 'W' || option == 'w')
{
printMenu();
}
if(option == 'C' || option == 'c')
{
printMenu();
}
if(option == 'U' || option == 'u')
{
printMenu();
}
if(option == 'E' || option == 'e')
{
printMenu();
}
if(option == 'Q' || option == 'q')
{
exit(0);
}
option = getchar();
}/*end while*/
system("pause");
}/*end main*/
sample output:
---------------------------------------------------------
| (N)ew record (D)isplay db (U)pdate record |
| (L)oad disk (W)rite disk (E)mpty disk |
| (S)ort db (C)lear db (Q)uit |
---------------------------------------------------------
choose one: n
name: judy
age: 30
high bp: 110
low bp: 88
3
---------------------------------------------------------
| (N)ew record (D)isplay db (U)pdate record |
| (L)oad disk (W)rite disk (E)mpty disk |
| (S)ort db (C)lear db (Q)uit |
---------------------------------------------------------
choose one: n
name: cindy white
age: 52
high bp: 100.7
low bp: 89.4
---------------------------------------------------------
| (N)ew record (D)isplay db (U)pdate record |
| (L)oad disk (W)rite disk (E)mpty disk |
| (S)ort db (C)lear db (Q)uit |
---------------------------------------------------------
choose one: d
===============================
name: udy
age: 30
bp: 110.00 88.00
risk: 1.0
name: indy white
age: 52
bp: 100.70 89.40
risk: 1.5
========== 2 records ==========
Your while loop and use of gets() is generally not good practice.
Try something like:
fflush(stdin);
fgets(pRecords[counter]->name, sizeof(pRecords[counter]->name), stdin);
Try
if (strlen(pRecords[counter]->name) > 0)
{
pRecords[counter]->name[strlen(pRecords[counter]->name) - 1] = '\0';
}
You lose the first character to while(getchar()=='\n');. I don't know why that statement is necessary, but it loops until it gets a character that is not '\n' (which is 'j' and 'c' in your case).
while (getchar() == '\n');
This line eats the newlines plus one character. When getchar() does not return a newline, it has already consumed the first character.
Look at ungetc() to write that character back onto the stream.
This:
while(getchar()=='\n');
loops until it gets a non-newline, which will be the first character of the name.
Try this instead:
do
c = getchar();
while(c == '\n');
ungetc(c, stdin);

Resources