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();
Related
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
I want to read the content of a website (http://www.google.com) in an Android app. Using the deprecated DefaultHttpClient still works fine and I always get a content length of about 15.000 characters:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet g = new HttpGet(target);
HttpResponse res = client.execute(g);
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return Base64.encodeToString(builder.toString().getBytes(), Base64.NO_WRAP);
However, when I use a HttpURLConnection to achieve the same, I get a different content with a length of about 100.000 characters.
HttpURLConnection connection = (HttpURLConnection) new URL(target).openConnection();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return Base64.encodeToString(builder.toString().getBytes(), Base64.NO_WRAP);
Does anybody know, why there is such a big difference. Thanks!
The problem is caused by the user agent. With the following code, the two requests behave the same:
connection.setRequestProperty("User-Agent","Apache-HttpClient");
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 need to insert post request data into array. I will get three sets of JSON information and I want to insert each JSON result in a String array. Here is the code I am currently using.
URL url = new URL("http://localhost:9090/service.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer response = new StringBuffer();
int i = 0;
ArrayList<String> arr = new ArrayList<String>();
while ((line = reader.readLine()) != null) {
response.append(line);
arr.add(response.toString());
System.out.println(arr.get(i));
i++;
}
If input like:
abc
def
ghi
This code outputs like:
abc
abcdef
abcdefghi
But I need output like input.
Move
StringBuffer response = new StringBuffer();
to the first line in your 'while' block
You have not reinitialized your StringBuffer variable response. In addition, you don't really need to use StringBuffer, since you are not manipulating the string information. I suggest you try the following (and at some point you won't want to use localhost):
URL url = new URL("http://localhost:9090/service.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int i = 0;
ArrayList<String> arr = new ArrayList<String>();
while ((line = reader.readLine()) != null) {
arr.add(line);
// debug information
System.out.println(arr.get(i));
i++;
}
change arr.add(response.toString()); to arr.add(line); and it works.
I use a PrintWriter out object. I write data out.println(some data) and close it with a out.close
URL url = new URL(myurl);
URLConnection connection = null;
PrintWriter out = null; BufferedReader br = null; connection = url.openConnection(); connection.setDoOutput(true);
out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()),true);
while(iterations) {
//print data on writer
out.println(object);
}
//closig print writer
out.flush();
out.close();
//Response from server
br = new BufferedReader(new InputStreamReader(connection.getInputStream())); // Get Exception in //this line EOF Exception
String temp;
while(temp = br.readLine() !=null) {
//do something
}
br.close();
URL url = new URL(myurl);
URLConnection connection = null;
PrintWriter out = null; BufferedReader br = null; connection = url.openConnection(); connection.setDoOutput(true);
out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()),true);
while(iterations)
{
//print data on writer
out.println(object);
}
//closig print writer
out.flush();
//Response from server
br = new BufferedReader(new InputStreamReader(connection.getInputStream())); // Get Exception in //this line EOF Exception
String temp;
while(temp = br.readLine() !=null)
{ //do something }
out.close();
Have a look at the code, you just had to put out.close instead of br.close at the end.