I have a problem about string converter
I read the content from url
http://suggestqueries.google.com/complete/search?client=firefox&hl=us&ds=yt&q=spinner
and the result IN CONSOLE is
["spinner",["spinner","spinner tricks","spinner fidget","spinner vietnam","spinner skill","spinner toy","spinner fidget toy","spinner vn","spinner hand","spinner vi\u1EC7t nam"]]
it contains string "spinner vi\u1EC7t nam", but when read it BY OS, i see "việt nam"
The question is how i can read content of api to see "việt nam" as result.
Below is my raw code
```
URL url = new URL("http://suggestqueries.google.com/complete/search?client=firefox&hl=us&ds=yt&q=spinner");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while((line=bufferedReader.readLine()) != null){
System.out.println(line);
}
bufferedReader.close();
reader.close();
```
Try this.
static final Pattern UNICODE = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
static String decodeUnicodeEscape(String s) {
Matcher m = UNICODE.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find())
m.appendReplacement(sb,
String.valueOf((char)Integer.parseInt(m.group(1), 16)));
m.appendTail(sb);
return sb.toString();
}
and
System.out.println(decodeUnicodeEscape(" vi\\u1EC7t nam"));
result
việt nam
Related
I'm using openstreetmap
I can only see the inputstream inside the while loop
Here's my code inside the initialize of the javafx Controller:
try {
URL myurl;
myurl = new URL("https://nominatim.openstreetmap.org/search?q=The+White+House,+Washington+DC&format=json&addressdetails=1");
URLConnection yc = myurl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
} catch (IOException ex) {
Logger.getLogger(WeatherUpdateController.class.getName()).log(Level.SEVERE, null, ex);
}
I am trying to get the StringBuffer inside a string variable so I can search it.
Use StringBuffer#toString() like so:
String str = response.toString();
Please note that you can use StringBuilder instead if you don't need synchronization. Source here
Error:
E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
I have to send image to server with post method but I cant send. Json came to me null. There is my code:
if (method.equalsIgnoreCase("POST")) {
URL url_ = new URL(url);
String paramString = URLEncodedUtils.format(params, "utf-8"); // unused
HttpURLConnection httpConnection = (HttpURLConnection) url_.openConnection();
httpConnection.setReadTimeout(10000);
httpConnection.setConnectTimeout(15000);
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
InputStream in = httpConnection.getInputStream();
OutputStream out = new FileOutputStream(picturePath);
copy(in, out);
out.flush();
out.close();
httpConnection.connect();
//Read 2
BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
String line2 = null;
StringBuilder sb = new StringBuilder();
while ((line2 = br.readLine()) != null) {
sb.append(line2);
}
br.close();
json = sb.toString();
}
How can I send image to server?
Thanks..
I am creating this method which takes an InputStream as parameter, but the readLine() function is returning null. While debugging, inputstream is not empty.
else if (requestedMessage instanceof BytesMessage) {
BytesMessage bytesMessage = (BytesMessage) requestedMessage;
byte[] sourceBytes = new byte[(int) bytesMessage.getBodyLength()];
bytesMessage.readBytes(sourceBytes);
String strFileContent = new String(sourceBytes);
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(sourceBytes);
InputStream inputStrm = (InputStream) byteInputStream;
processMessage(inputStrm, requestedMessage);
}
public void processMessage(InputStream inputStrm, javax.jms.Message requestedMessage) {
String externalmessage = tradeEntryTrsMessageHandler.convertInputStringToString(inputStrm);
}
public String convertInputStringToString(InputStream inputStream) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
Kindly try this,
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
i believe that raw data as it is taken is not formatted to follow a character set. so by mentioning UTF-8 (U from Universal Character Set + Transformation Format—8-bit might help
Are you sure you are initializing and passing a valid InputStream to the function?
Also, just FYI maybe you were trying to name your function convertInputStreamToString instead of convertInputStringToString?
Here are two other ways of converting your InputStream to String, try these maybe?
1.
String theString = IOUtils.toString(inputStream, encoding);
2.
public String convertInputStringToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is, encoding).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
EDIT:
You needn't explicitly convert ByteArrayInputStream to InputStream. You could do directly:
InputStream inputStrm = new ByteArrayInputStream(sourceBytes);
I tried putting a toast before the return statement but the String variable returns an empty string.
public String getXmlFile(String pathFile, Context context){
String xmlFileString = "";
AssetManager am = context.getAssets();
try {
InputStream str = am.open(pathFile);
int length = str.available();
byte[] data = new byte[length];
xmlFileString = new String(data);
} catch (IOException e1) {
e1.printStackTrace();
}
return xmlFileString;
}
use this to read byte[] from InputStream:
public byte[] convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString().getBytes("UTF-8");
}
Use this to read the XML. Without passing UTF-8 to the InputStreamReader you might get a broken XML string.
BufferedReader reader = new BufferedReader(new InputStreamReader(
context.getAssets().open(pathFile), HTTP.UTF_8));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
Now when parsing the string to XML in my case there was also the problem that each line break was interpreted as an own XML node. Spaces also were an issue. Use this on the string read above to fix that:
String oneLineXml = sb.toString().replace("\n", "").replaceAll("> +<", "><");
Only then you should parse the string, like this:
Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new ByteArrayInputStream(
oneLineXml.getBytes(HTTP.UTF_8))));
URL u = new URL(url);
String expected = "";
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
InputStream in = new BufferedInputStream(uc.getInputStream());
Reader r= new InputStreamReader(in);
so here is my code and i want a very little help that is the above is to fetch the content from url but now i want to use the same code for reading content from file what i need to change in above code....i mean there should be something which i need to change in the place of uc.getInputStream()...so what is that
InputStream in = new BufferedInputStream(uc.getInputStream());
Look at class FileInputStream.
You can simply user that code and do it in similar way.
InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
reader.close();