Do I need 3 try blocks for url encode? - java

I tried this:
String query = "http://maps.googleapis.com/maps/api/geocode/xml?address="+country+"+"+province+"+"+city+"&sensor=false";
try {
query = URLEncoder.encode(query, "UTF-8");
}
catch (Exception e) {
println("getLatLonFromAdress URLEncoder error: "+e);
return new float[] { -1f, -1f };
}
but it turns the url into:
http%3A%2F%2Fmaps.googleapis.com%2Fmaps%2Fapi%2Fgeocode%2Fxml%3Faddress%3DCanada%2BAlberta%2BGrande+Cache%26sensor%3Dfalse
So I only want to encode country, province and city. Is it bad to handle that in one try block? Like:
try {
country = URLEncoder.encode(country, "UTF-8");
province = URLEncoder.encode(province, "UTF-8");
city = URLEncoder.encode(city, "UTF-8");
}
catch (Exception e) {…}

The UnsupportedEncodingException will not be thrown if you are passing "UTF-8" as that will always be present. Therefor you can happily handle them all in 1 catch.

Related

Convert Clob to String

How can I get String out of Clob. I did google it, but
myClob.getSubString(0, (int) info.length()));
is the only thing I get. Console says:
java.sql.SQLException: Invalid argument(s) in call at
oracle.sql.CLOB.getSubString(CLOB.java:278) at
ru.tenet.es09.dao.CompanyDAOImpl.get(CompanyDAOImpl.java:72) at
ru.tenet.es09.dao.CompanyDAOImpl.getList(CompanyDAOImpl.java:132) at
ru.tenet.es09.dao.AddressDAOImpl.getList(AddressDAOImpl.java:59) at
ru.tenet.es09.Test.main(Test.java:11)
It points on getSubString() method. What is wrong?
Assuming you're using standard JDBC, once you have a ResultSet object you should be able to call ResultSet#getString("clob_field_name") to retrieve your CLOB data.
I know I'm late to this party!. Here is the one liner i used from hibernate library. If hibernate is already integrated to project then we can use annotations to convert clob to java String. In my case i had custom result transformer which read data from multiple tables after costly join. In the resultSetTransformer the below line does the job.
ClobType.INSTANCE.toString((Clob) tuple[2])
// org.hibernate.type.ClobType
this my way (sorry my english)
res = ps.executeQuery();
try {
while (res.next()) {
System.out.println(res.getClob(1));//confirm data
sRet = res.getString(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
ps.close();
}
Converting String to CLOB
SOobject.setLongStringField( new SerialClob(entityString.toCharArray()));//Converting String to CLOB
Convert Clob to String
public String getLongStringField() {
Reader reader = null;
BufferedReader bufferedReader = null;
try {
reader = longStringField.getCharacterStream();
bufferedReader = new BufferedReader(reader);
return IOUtils.toString(bufferedReader);
} catch (Exception e) {
throw new RuntimeException("Error while reading String from CLOB", e);
} finally {
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(bufferedReader);
}
}
I have created a java method which can create string from a CLOB object:
public String clobToString(Clob data) {
StringBuilder sb = new StringBuilder();
try {
Reader reader = data.getCharacterStream();
BufferedReader br = new BufferedReader(reader);
String line;
while(null != (line = br.readLine())) {
sb.append(line);
}
br.close();
} catch (SQLException e) {
// handle this exception
} catch (IOException e) {
// handle this exception
}
return sb.toString();
}

ILLEGALSTATEEXCEPTION : Target host must not be null

I have tried multiple solutions here but none seem to work. I am getting error at String imageJsonStr = sh2.makeServiceCall(imgUrl[i], ServiceHandler.GET);
There are no special characters in string and variable imageId is a string containing only numbers like '98546214265231'
imgUrl[i] = "https://graph.facebook.com/v2.2/"
+ imageId
+ "?access_token="
+ static_token;
try {
try {
imgUrl[i] = URLEncoder.encode(imgUrl[i],"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String imageJsonStr = sh2.makeServiceCall(
imgUrl[i], ServiceHandler.GET);
Java URL encoding of query string parameters refer this.. you need not encode the entire url .. encode only the parmaters

JSONException: Value of type java.lang.String cannot be converted to JSONArray

There are codes I am using:
try {
resultObject = new JSONObject(URLDecoder.decode(result, "UTF-8"));// no problem here
resultJsonArray = resultObject.getJSONArray("data"); // error comes when run this line.
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
This is the whole error information:
org.json.JSONException: Value [{"first_name":"aig","phone_no":"3659428","passcode":"aig","last_name":"aig","user_id":"03343785-2714-43a5-a566-f4d9877ccafa","email_id":"aig.science#gmail.com"},{"first_name":"aig","phone_no":"635448448","passcode":"aig","last_name":"aig","user_id":"5dc26dcc-3f81-434a-b293-48438f2f920a","email_id":"aig.science#gmail.com"}] at data of type java.lang.String cannot be converted to JSONArray
After being formatted(http://jsonformatter.curiousconcept.com/), the JSON string will be like this:
{
"response":"Success",
"tablename":"USER_INFO",
"transaction_type":"MODIFICATION_PULL_RESPONSE",
"data":"[{\"first_name\":\"aig\",\"phone_no\":\"3659428\",\"passcode\":\"aig\",\"last_name\":\"aig\",\"user_id\":\"03343785-2714-43a5-a566-f4d9877ccafa\",\"email_id\":\"aig.science#gmail.com\"},{\"first_name\":\"aig\",\"phone_no\":\"635448448\",\"passcode\":\"aig\",\"last_name\":\"aig\",\"user_id\":\"5dc26dcc-3f81-434a-b293-48438f2f920a\",\"email_id\":\"aig.science#gmail.com\"}]"
}
Please avoid the ""(Double quote characters) directly cause JSON through an exception while parsing it, always use \ Before these characters,
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
.It may help you.
you doing wrong. try like below code:
try {
resultJsonArray = resultObject.getJSONArray(result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
After testing for a while, I solved it in a wired way:
**Before:**
try {
resultObject = new JSONObject(URLDecoder.decode(result, "UTF-8"));// no problem here
resultJsonArray = resultObject.getJSONArray("data"); // error comes when run this line.
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
**After**
try {
resultObject = new JSONObject(URLDecoder.decode(result, "UTF-8"));// no problem here
resultJsonArray = new JSONArray(resultObject.get("data").toString()); // Works!!!
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
It is really wired. I have no idea why this works.

cannot read arabic text from url in java

I've a web service that prints the following text.
[{"packid":"p101","title":"صفته 1","description":"شسیب: 1\r\nثق س: 50","linkfuntext":"funtext","linkshortstory":"short","linkfunpic":"pic","linkringtone":"ring","linkfungif":"gif","linkwallpaper":"wall","price":"500","buyid":"pack.fun.1","buyed":""},{"packid":"p102","title":"بسته صدا","description":" متن ها: 50\r\nصداها: 120\r\nتصاویر: 100\r\nتصاویر متحرک: 50\r\nداستان کوتاه: 20","linkfuntext":"","linkshortstory":"","linkfunpic":"","linkringtone":"","linkfungif":"","linkwallpaper":"","price":"1200","buyid":"fun.pack.2","buyed":""}]
When I try to read it in java I receive it in the following format
[{"packid":"p101","title":"صفته 1","description":"شسیب: 1\r\nثق س: 50","linkfuntext":"funtext","linkshortstory":"short","linkfunpic":"pic","linkringtone":"ring","linkfungif":"gif","linkwallpaper":"wall","price":"500","buyid":"pack.fun.1","buyed":""},{"packid":"p102","title":"بسته صدا","description":" متن ها: 50\r\nصداها: 120\r\nتصاویر: 100\r\nتصاویر متحرک: 50\r\nداستان کوتاه: 20","linkfuntext":"","linkshortstory":"","linkfunpic":"","linkringtone":"","linkfungif":"","linkwallpaper":"","price":"1200","buyid":"fun.pack.2","buyed":""}]
I've tried changing the character set to UTF-8 as well as ISO-8859-6 but still no luck. When I print the text on console it is printed correctly which means there is no issue in character set of eclipse or console. Also I've tried changing the character set of string that is storing the text, but same issue.
String serverOutput = new String(TEXT_FROM_SERVER.getBytes(), "UTF-8");
Here is my code that gets output from web service
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String serverOutput = convertStreamToString(is);
private String convertStreamToString(InputStream is) {
Reader rd = null;
BufferedReader reader = null;
try {
rd = new InputStreamReader(is,"UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
reader = new BufferedReader(rd);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Any kind of help will be greatly appreciated. Thanks
you need to unescape those HTML characters, and you can do so with a method from Apache Commons Lang called unescapeHtml. More info here.
Example:
String afterDecoding = StringEscapeUtils.unescapeHtml(beforeDecoding);

how to get a value by key from an json (or xml) string?

In the android app I get an xml or json string returned, However, I cant seem to figure out any way on how to get an value from the string in any way by entering an key.
In PHP you just use something like $myArray['parent']['child'] but I have no clue on how this works in java.
Any idea's would be greatly appreciated! (an example for both XML and JSON even more ;) )
Here's what I would do:
locate an XML/JSON library (there's tons) (google-gson for json)
read the documentation to find a parse method ((new JsonParser()).parse(text))
read the documentation to find out what the return value is (JsonElement)
decide what you want to do with the parsed data (myJsonObj.get(...))
write the code
public class parsingjsontest2 extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(main);
String str = connect("http://rentopoly.com/ajax.php?query=Bo"));
System.out.println("String::"+str);
}
}
private String connect(String url)
{
// Create the httpclient
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
// return string
String returnString = null;
try {
// Open the webpage.
response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode() == 200){
// Connection was established. Get the content.
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
// Load the requested page converted to a string into a JSONObject.
JSONObject myAwway = new JSONObject(convertStreamToString(instream));
// Get the query value'
String query = myAwway.getString("query");
**// Make array of the suggestions
JSONArray suggestions = myAwway.getJSONArray("suggestions");
// Build the return string.
returnString = "Found: " + suggestions.length() + " locations for " + query;
for (int i = 0; i < suggestions.length(); i++) {
returnString += "\n\t" + suggestions.getString(i);
}
// Cose the stream.
instream.close();
}
}
else {
// code here for a response othet than 200. A response 200 means the webpage was ok
// Other codes include 404 - not found, 301 - redirect etc...
// Display the response line.
returnString = "Unable to load page - " + response.getStatusLine();
}
}
catch (IOException ex) {
// thrown by line 80 - getContent();
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
catch (JSONException ex){
// JSON errors
returnString = "JSON failed; " + ex.getMessage();
}
return returnString;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
As you didn't specify what kind of xml you are trying to read, I'm answering based on what I know.
In Android, if you were talking about the layout and strings.xml files, you use a dot (.) operator, like R.string.appname.
Please post more details about your specific problem, if this is not what you were looking for.

Categories

Resources