I want a url that will look like this
"http://example.com/get_item_data.php?uid="inv_no"
I tried URL encoder, but could not figure it out,
I first tried this, it did not work
try {
json_url = "http://example.com/get_item_data.php?uid="+ URLEncoder.encode(inv_no, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
then this
try {
json_url = "http://example.com/get_item_data.php?uid="+ URLEncoder.encode("inv_no", "UTF-8") + "=" + URLEncoder.encode(inv_no, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
yet, no result, please help
Usually you don't have to quote your parameters. So to me your first trial is correct:
json_url = "http://example.com/get_item_data.php?uid="+
URLEncoder.encode( inv_no, "UTF-8");
Not sure about what you're trying to do, but looking at your question I suggest the following code:
try {
json_url = "http://example.com/get_item_data.php?uid=\""+
URLEncoder.encode( inv_no, "UTF-8") + "\"";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
In this case you have the quote outside the encoded parameter inv_no.
Or even:
try {
json_url = "http://example.com/get_item_data.php?uid="+
URLEncoder.encode("\"" + inv_no + "\"", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
In this case the parameter inv_no and the quotes will be encoded.
try {
String json_url = "\"http://example.com/get_item_data.php?uid=\"inv_no\"";
System.out.println(json_url);
} catch (Exception e) {
e.printStackTrace();
}
Encode the whole string AFTER you added your ´inv_no´-variable.
try {
json_url = URLEncoder.encode('http://example.com/get_item_data.php?uid='+inv_no, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Related
I have this code where I wanted to rename the before saving it to the file system. I tried other questions here in stack overflow but it doesn't apply for me. Hoping you could help me this is my code.
#PostMapping("/api/file/upload")
public #ResponseBody String uploadMultipartFile(#RequestParam("uploadfile") MultipartFile file) {
try {
fileStorage.store(file);
return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
} catch (Exception e) {
return "Error -> message = " + e.getMessage();
}
}
This is my store function:
#Override
public void store(MultipartFile file){
try {
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (Exception e) {
throw new RuntimeException("FAIL2! -> message2 = " + e.getMessage());
}
}
I tried renaming the original file but it doesn't work.
Hoping you could help me. Thank you so much!!!
Below is working snippet with little modification here and there :
#PostMapping(value = "/api/file/upload", headers = {"content-type=multipart/*"})
public #ResponseBody String uploadMultipartFile(#RequestParam("uploadfile") MultipartFile file) {
Path TO = Paths.get("/Users/myusername/Desktop/newfileName");
try {
try {
Files.copy(file.getInputStream(), TO);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("FAIL2! -> message2 = " + e.getMessage());
}
return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
return "Error -> message = " + e.getMessage();
}
}
OutputScreen:
I have a Json String to encode
String strMappingList = [{"Id": "67","AccessType": "2"},{"Id": "1111","AccessType": "2"},{"Id": "1166","AccessType": "2"}]
When I did url encoding it encodes strMappingList twice
try {
String str = URLEncoder.encode(strMappingList, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Try the code you take in strings file
if you get response from server that fine not use in string.xml you use direct
in string.xml
<string name="urls">[{"Id": "67","AccessType": "2"},{"Id": "1111","AccessType": "2"},{"Id": "1166","AccessType": "2"}]</string>
Code
String strMappingList = getResources().getString(R.string.urls);
try {
String str = URLEncoder.encode(strMappingList, "UTF-8");
System.out.println("Strings"+str);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Output Single time
%5B%7BId%3A+67%2CAccessType%3A+2%7D%2C%7BId%3A+1111%2CAccessType%3A+2%7D%2C%7BId%3A+1166%2CAccessType%3A+2%7D%5D
I am developing a project which involves JSON manipulation in Java using JSON API. There are many places where I need to read values from JSON file. The API provides checked exceptions for the same. Everytime I use the API to read JSON values, I am forced to write try catch block. As a result, there is a large number of try catch blocks. It makes the code look messy.
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
}
catch(Exception e) {
System.out.println("File Not found");
}
try {
while((line = read.readLine() ) != null) {
Content = Content+line;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
ResponseArr = new JSONArray( Content );
} catch (JSONException e) {
e.printStackTrace();
}
try {
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
}
try {
StoreResponse = ResponseArr.getJSONObject(0).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
}
Is there any way to avoid this ?A single try catch block would not suffice and the statements are not dependent. Each read statement requires a separate try catch block as I have to log the details of places while catching the exception. Can I invoke a common method whenever I have a code to read JSON data, like sending the code as a paramater to a method which would take care of the exception handling or some other way round ?
Since (all?) the subsequent statements are dependent on the previous it makes no sense having that many try/catch blocks. I would rather put the code inside one try/catch and handle the exceptions by type
Pseudo-code:
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
} catch(FileNotFoundException)
System.out.println("File Not found");
}
// and so on
As some are suggesting, you might want to let all these exceptions bubble up (not catching them) since you're not doing anything meaningful when catching them. However, I think that depends on the calling context.
If you are handling all exceptions in the same way, why not combine them in one try/ catch clause
for example like this :
try {
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (Exception e) {
e.printStackTrace();
}
Try like this
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
catch(Exception e) {
System.out.println("File Not found");
}
I'm trying to download this html
I'm using this code:
Document doc = null;
try {
doc =Jsoup.connect(link).userAgent("Mozilla").get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i ("html", doc.toString());
UPDATED:
ASLO tried to use it:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(link);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
//
e1.printStackTrace();
} catch (IOException e1) {
//
e1.printStackTrace();
}
InputStream in = null;
try {
in = response.getEntity().getContent();
} catch (IllegalStateException e1) {
//
e1.printStackTrace();
} catch (IOException e1) {
//
e1.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
} catch (UnsupportedEncodingException e) {
//
e.printStackTrace();
}
StringBuilder str = new StringBuilder();
String line = null;
try {
while((line = reader.readLine()) != null)
{
str.append(line);
}
} catch (IOException e1) {
//
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
//
e1.printStackTrace();
}
String html = str.toString();
Log.e("html", html);
again responce like this one:
<html>
<body>
<script>document.cookie="BPC=f563534535121d5a1ba5bd1e153b";
document.location.href="http://...link.../all?attempt=1";</script>
</body>
</html>
I can't find any solution... Page can not be downloaded maybe because haven't cookie ... or what?
In the script tag, you have this statement :
document.location.href="....link..../all?attempt=1";
Normally it forces the browser to reload the page with the location. I think it's the page "....link...?attempt=1" that you want to download in fact.
It is not sure that it will work anyway if you don't use the cookie defined in the script but it deserves a try.
I have two arrays that I want to print to separate files. Here's my code:
try {
PrintStream out = new PrintStream(new FileOutputStream(
"Edges.txt"));
for (i = 0; i < bcount; i++) {
out.println(b[i][0] + " " + b[i][1]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
PrintStream out = new PrintStream(new FileOutputStream(
"Nodes.txt"));
for (i = 0; i < bigbIter; i++) {
out.println(bigb[i]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
If I only use the first set of try / catch / catch, it works perfectly. But when I use both it doesn't work, giving me the errors "illegal start of type ... } catch" and "error: class, interface, or enum expected". What am I doing wrong?
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
You have an extra }, which throws off the parser and gives you lots of errors.
You should write a method to write to the file. Just pass the file name and data. You should see that you have too many closing brackets, get your IDE to highlight brackets.
Lesson is just don't copy/paste and then edit the catch block when you want it again!
Edit: Also in java 7 you can have multiple catches in one block, it is better to do this:
catch (FileNotFoundException | IOException e)
{
}