I am making an android app that uses theMovieDB API.
Look at the part of my class extending AsyncTask.
private HttpURLConnection urlconnection = null;
private URL url;
protected String doInBackground(String[] task)
{
String DATA=null;
String baseAddress="https://api.themoviedb.org/3/movie/";
String apiKey="225b36fd29826b4c9821dd90bfc4e055";
Uri Url = Uri.parse(baseAddress).buildUpon().appendEncodedPath(task[0]).appendQueryParameter("api_key",apiKey).build();
Log.d("built URL",Url.toString());
try
{
url= new URL(Url.toString());
urlconnection= (HttpURLConnection) url.openConnection();
urlconnection.setRequestMethod("GET");
urlconnection.connect();
InputStream inputStream = urlconnection.getInputStream();
if (inputStream==null)
{
return null;
}
BufferedReader reader= new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer=null;
String line;
while ((line=reader.readLine())!=null)
{
buffer.append(line+'\n');
}
DATA=buffer.toString();
}
I am getting IOException (seen in logcat). I checked the built URL on the browser(it was working). The Same set of syntax did work on openweather api. Is there any other thing that themovieDb API need? Help me Solve it. I did check there documentation but there was no info for android.
i got the Solution. I was connected to my mobile hotspot which due to some reason does not work as expected. Switching to my home WIFI fixed the issue.
Thanks for giving your time on my question
Related
I try to implement download function with HttpURLConnection and function work, but when the file suffix is ".deb" e.g. file1.deb, file2.deb, download the file is not complete.
why?
this my code
DownloadInfo downloadFile(String source, String saveDirectory)throws HTTPException {
URL url = new URL(source);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new HTTPException(responseCode);
}
String httpContent = getResponseHeadContent(connection);
Path saveFilePath = produceSavePath(source, saveDirectory);
Files.copy(connection.getInputStream(), saveFilePath, StandardCopyOption.REPLACE_EXISTING);
connection.disconnect();
DownloadInfo info = new DownloadInfo();
info.setFilePath(saveFilePath);
info.setHttpHeadContent(httpContent);
return info;
}
I got the reason because of link server is IIS. IIS does not serve the unknown file type, then ".deb" not in MIME type. I must manual to add it.
As we all know both these codes will yield the same result
public class MainApp {
public static void main(String[] args) throws IOException {
URL google = new URL("http://www.google.com");
google.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(google.openStream()));
reader.lines().forEach(System.out::println);
}
}
and
public class MainApp {
public static void main(String[] args) throws IOException {
URL google = new URL("http://www.google.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(google.openStream()));
reader.lines().forEach(System.out::println);
}
}
So what's the point in using google.openConnection()?
May be javadoc for this method helps:
public java.net.URLConnection openConnection() throws java.io.IOException
Returns a URLConnection instance that represents a connection to the remote object referred to by the URL. A new instance
of URLConnection is created every time when invoking the
URLStreamHandler.openConnection(URL) method of the protocol handler
for this URL.
It should be noted that a URLConnection instance does not establish
the actual network connection on creation. This will happen only when
calling URLConnection.connect().
If for the URL's protocol (such as HTTP or JAR), there exists a
public, specialized URLConnection subclass belonging to one of the
following packages or one of their subpackages: java.lang, java.io,
java.util, java.net, the connection returned will be of that subclass.
For example, for HTTP an HttpURLConnection will be returned, and for
JAR a JarURLConnection will be returned.
Use this if you want to add some specific connectivity properties to your connection.
For example:
URLConnection urlConnection = google.openConnection();
urlConnection.setReadTimeout(1000);
urlConnection.setConnectTimeout(1000);
Since the code for openStream() is:
public final InputStream openStream() throws java.io.IOException {
return openConnection().getInputStream();
}
It seems quite redundant indeed.
But if I were you, if I openConnection()d, I would then get the InputStream on the returned URLConnection.
openConnection() does not modify the URL object, it returns a URLConnection instance that you could then use. The code in the question ignores the return value of openConnection(), so, in this case, it's indeed pointless. it would only be useful if you actually do something with this connection object, such as, e.g., modifying its timeout:
URL google = new URL("http://www.google.com");
URLConnection conn = google.openConnection();
conn.setTimeout(7); // just an example
BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
reader.lines().forEach(System.out::println);
I have a API that takes a string and converts in into audio when I do a HTTP get in android. I want to be able to play it back when I recieve it but I don't know how to do this. Can someone help me. Here is my code so far:
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
Currently, I'm working on tuneup client/server application communicated via http using HttpURLConnection.
Here, the client sends a java-serializable object as the request to a server (HttpServlet receives this) and it receives a JSON string as the response.
Then that JSON response is forwarded to a JSON parser to process.
Previously, first we downloaded and constructed the complete JSON string comming through the stream and then we forwarded it to the parser. Then I tuned it up to forward the stream it-self to the parser (Jackson Streaming parser) and let it to process on the part that it receives without waiting to download the entire JSON string.
This gives good results when the download speed is good. But here I'm getting not that much good results in one environment, since it is getting so much time to download and it process very faster. (sometimes 17(s) to download 4-5MB JSON string).
How can tune this up to download and parse the JSON faster than this?
Client
URL url = new URL(http://myhost.com/Connectors/url2Service);
HttpURLConnection servletConnection = (HttpURLConnection) url.openConnection();
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);
servletConnection.setRequestMethod("POST");
servletConnection.setRequestProperty("content-type","application/x-java-serialized-object");
servletConnection.setRequestProperty("Accept","application/json");
servletConnection.setRequestProperty("Accept-Encoding","gzip,deflate");
servletConnection.setRequestProperty("user-agent","Mozilla(MSIE)");
servletConnection.setConnectTimeout(30000);
servletConnection.setReadTimeout(60000);
servletConnection.connect();
String encodingHeader = servletConnection.getHeaderField("Content-Encoding");
String contentType = servletConnection.getHeaderField("content-type");
if(contentType.equals("application/json")){
InputStream inputStream = servletConnection.getInputStream();
if(encodingHeader != null && encodingHeader.toLowerCase().indexOf("gzip") != -1) {
gzipis = new GZIPInputStream(inputStream);
} else {
iSR = new InputStreamReader(inputStream);
br = new BufferedReader(iSR);
}
ResposeObject resposeObject = new JsonString2ResposeObject().parse(gzipis); // previously we passed complete String here
}
Server
public class url2Service extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
RequestObject requestObject = (RequestObject) ois.readObject();
response.setContentType("application/json");
String jsonResponseString = new ServerApplication().doMoreWithRequest(requestObject);
OutputStreamWriter wr = null;
if (null != aEncoding && aEncoding.toLowerCase().indexOf("gzip") != -1) {
gzipos = new GZIPOutputStream(response.getOutputStream());
wr = new OutputStreamWriter(gzipos);
response.addHeader("Content-Encoding", "gzip,deflate");
} else {
wr = new OutputStreamWriter(response.getOutputStream());
}
wr.write(jsonString);
wr.flush();
}
}
I am currently writing program to communicate with a device in my network, and the following code is what I have so far, it passed authentication and can get the webpage from the device, however i couldnt get the GET request to work, when I run the code below, i get the error:
Exception in thread "main" java.io.FileNotFoundException: http://192.168.100.222:80
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
when I input data on the webpage, its equivalent of going http://l192.168.xxx.xxx/2?A=3&p=1&X=1234, and from tcpflow, it does GET /2?A=4&p=1&X=1234 HTTP/1.1,
I tried creating a new url connection with http://192.168.xxx.xxx/2?A=3&p=1&X=1234, and it worked, but i have multiple input options and i dont want to create a new connection for each of them, how can I do the equivalent while staying connected? or what I did wrong in the code?
thanks in advance.
public class main {
public static void main(String[] argv) throws Exception {
Authenticator.setDefault(new MyAuthenticator());
URL url = new URL("http://192.168.xxx.xxx");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("Get /2?A=4&p=1&X=1234 HTTP1.1");
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
I don't want to create a new connection for each of them
Don't worry about that. HttpURLConnection does connection pooling under the hood. Just use your actual URLs, don't try to out-think Java.