Reputation: 1575
Any possibilities to convert the HttpURLconnection
response in ASCII? Can I have the sample code of it?
Upvotes: 0
Views: 637
Reputation: 26142
HttpURLconnection yourConnection = getConnectionSomeWay();
InputStream inputStream = yourConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream, "US-ASCII");
BufferedReader bufferedReader = new BufferedReader(reader);
System.out.println(bufferedReader.readLine());
Or, shorter version:
HttpURLconnection yourConnection = getConnectionSomeWay();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(yourConnection.getInputStream(), "US-ASCII"));
System.out.println(bufferedReader.readLine());
Or in case you meant writing response in ASCII, then it's mostly the same way:
HttpURLconnection yourConnection = getConnectionSomeWay();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(yourConnection.getOutputStream(), "US-ASCII"));
bufferedWriter.write("Hello world!");
bufferedWriter.flush();
Upvotes: 2
Reputation: 2521
getContent
public Object getContent() throws IOException
Retrieves the contents of this URL connection.
This method first determines the content type of the object by calling the getContentType method. If this is the first time that the application has seen that specific content type, a content handler for that content type is created:
If the application has set up a content handler factory instance using the setContentHandlerFactory method, the createContentHandler method of that instance is called with the content type as an argument; the result is a content handler for that content type.
If no content handler factory has yet been set up, or if the factory's createContentHandler method returns null, then the application loads the class named:
sun.net.www.content.<contentType>
where <contentType> is formed by taking the content-type string, replacing all slash characters with a period ('.'), and all other non-alphanumeric characters with the underscore character '_'. The alphanumeric characters are specifically the 26 uppercase ASCII letters 'A' through 'Z', the 26 lowercase ASCII letters 'a' through 'z', and the 10 ASCII digits '0' through '9'. If the specified class does not exist, or is not a subclass of ContentHandler, then an UnknownServiceException is thrown.
Returns:
the object fetched. The instanceof operator should be used to determine the specific kind of object returned.
Throws:
IOException - if an I/O error occurs while getting the content.
UnknownServiceException - if the protocol does not support the content type.
See Also:
ContentHandlerFactory.createContentHandler(java.lang.String), getContentType(), setContentHandlerFactory(java.net.ContentHandlerFactory)
Upvotes: 1