I am trying to download an image from the below URL but it always returns HTML.
Do you know how to download it by java? The below code can download successfully other URL like (http://example.com/img/abc.jpg)
URL
https://www.ttbonline.gov/colasonline/publicViewAttachment.do?filename=Sankaty%20Body.JPG&filetype=l
Code
private static void getImages(String src) throws IOException {
URL url = new URL(src);
InputStream in = url.openStream();
FileUtils.copyURLToFile(
url,
new File("C:\\Users\\admin\\Desktop\\output\\img.jpeg"),
10000,
10000);
in.close();
}
Thanks in advance.
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.
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
I have a requirement of sending image from android client to Restful Web Service on a button click, for which I used the following code
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.myImage);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
encodedString = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
reqParams.put("image",encodedString);
client.post(IMAGE_POST_URL, reqParams, new AsyncHttpResponseHandler() {....});
I am able to send the image to the restful service and save it in MySql DB as Blob type.
Upon clicking another button I am receiving the image from restful web service as InputStream. But I am not able to convert to Bitmap and display on the screen using following code. Could someone light me up on where I am doing wrong.
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
inputStream = urlConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
imgView.setImageBitmap(imageBmp);
Any help is appreciated..
Here is the Rest service methods I am using ..
#POST
#Path("/uploadImage1")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response uploadImage1(#FormParam(value = "image") String image) {
InputStream is = new ByteArrayInputStream(image.getBytes());
.....(MySQL Code to insert as BLOB)}
#GET
#Path("/getImage")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getImage() {....
Response.ok(blob.getBinaryStream(), MediaType.APPLICATION_OCTET_STREAM).build();}
Based on your answers to comments, it appears that you are never performing a base64 decode step. You need to do that somewhere: either
at the point where you insert the Blob into the database, or
when you retrieve the Blob and send it to the peer, or
at the point where you receive it in the peer, before you turn it back into an image.
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");
Sorry im totally New to the Http, i Hardly Could Write a Http Server With Examples i have seen, and Im Trying to Download Images from this Http Server with Picasso Lib, but it seems Doesnt Work, here is my Server :
my content is : D:\Users\Default and im trying to load Default.jpg into iv:
public class SimpleHttpServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/info", new InfoHandler());
server.createContext("/get", new GetHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class InfoHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "Use /get to download an Image";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static class GetHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
// add the required response header for an Image file
Headers h = t.getResponseHeaders();
h.add("Content-Type", "image/jpg");
// a PDF (you provide your own!)
File file = new File ("D:/Users/Default/Default.jpg");
byte [] bytearray = new byte [(int)file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(bytearray, 0, bytearray.length);
// ok, we are ready to send the response.
t.sendResponseHeaders(200, file.length());
OutputStream os = t.getResponseBody();
os.write(bytearray,0,bytearray.length);
os.close();
}
}
}
and loading it from picasso like this:
Picasso.with(getActivity()).load(Uri.parse("http://192.168.1.103:8000/D:/Users
/Default/Default.jpg")).into(iv);
Which are my Mistakes and how funny they are? :P
Well first off, you hard-coded the file that the server will return, so you don't need the file location in your Uri.... you would use /get at the end... it even says so in your code... String response = "Use /get to download an Image";. Also, you need to add:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
to your manifest file if you have not already... It would be helpful FYI to post a log, not just ask whats wrong and not give any hints.