Download image form blob:http url in Java - java

i have images with src blob:https//....
like this :
-
to download the image I tested several techniques without results
I tried to load the image like the browser does (http get request)
public static void httpGetImage(String url, String path) {
//url ==> blob:https://www.colissimo.fr/5e50dd3d-5b7f-4861-b0ec-34e12f4f3af4
try {
HttpGet get = new HttpGet(url);
get.addHeader("content-type", "image/png");
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(get)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
try (FileOutputStream outstream = new FileOutputStream(new File(path))) {
entity.writeTo(outstream);
}
}
httpClient.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get this error :
org.apache.http.client.ClientProtocolException: URI does not specify avalid host name:blob:https://www.colissimo.fr/5f67d9be-43bb-489d-8746-cf8fccf2cac9

Related

Java URL downloading HTML content instead of file?

I am trying to download file using Java URL class, but it is downloading HTML content instead.
class DownloadFileHttpCilent {
public static void main(String[] args) throws Exception {
try {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(
"https://url");
String encoding=Base64.getEncoder().encodeToString(("abcd:pwd").getBytes());
request.setHeader("Authorization", "Basic " + encoding);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("Request Url: " + request.getURI());
System.out.println("Response Code: " + responseCode);
InputStream is = entity.getContent();
String filePath = "c:\\file1.zip";
FileOutputStream fos = new FileOutputStream(new File(filePath));
int inByte;
while ((inByte = is.read()) != -1) {
fos.write(inByte);
}
is.close();
fos.close();
client.close();
System.out.println("File Download Completed!!!");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
For other open source URLs, it's working fine, but only in this case, in which it is password protected, it is downloading HTML content.
Output:
Request Url: https://abcd.cahj.com/defj
Response Code: 200
File Download Completed!!!

How can I view the full URL after using MultipartEntityBuilder?

I am fairly confident this code works (I used it in another part of my project for a different API) as far as posting but I do not think the URL is being formatted correctly. I want to know if there is anyway to view the full URL after building all of the entities so I can see if the final URL is formatted correctly. Code:
My URL = http://pillbox.nlm.nih.gov/PHP/pillboxAPIService.php
Method = POST
API key = not going to post (works though)
drugName = just a string that has the name of a drug
I have logs in the code to try and view the url but they aren't returning anything close and the debugger isn't either.
I am trying to build the URL to look like this:
http://pillbox.nlm.nih.gov/PHP/pillboxAPIService.php?key=My_API_KEY&ingredient=diovan
public String makeServiceCallPillBox(String url, int method,
String api, String drugName)
{
String resultEnitity = null;
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpEntity entityResult = null;
// Checking http request method type
if (method == POST)
{
HttpPost httpPost = new HttpPost(url);
// Butild the parameters
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("key", api);
builder.addTextBody("ingredient", drugName);;
final HttpEntity entity = builder.build();
httpPost.setEntity(entity);
Log.d("url", httpPost.toString());
httpResponse = httpClient.execute(httpPost);
Log.d("post", builder.toString());
Log.d("post2", entity.toString());
entityResult = httpResponse.getEntity();
resultEnitity = EntityUtils.toString(entityResult);
Log.d("result", resultEnitity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultEnitity;
}
Any help is appreciated.

I have to close app and open again for android file upload to work

I have an Android application that records an audio file and uploads it to an API for fingerprinting. The app works well when it uploads for the first time and gets the right response. However, on trying to upload again the request from the app seems to reach the server without the uploaded file. Strangely, when I close the app completely and open it again, it works well. However, I want it to be able to do the uploads continuously without having to close it after every attempt.
Here is my code:
public class MainActivity extends Activity {
class UploadFileTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String responseString = "";
HttpResponse response = null;
try {
//below is the API url
String url = "http://1**.**.**.**:8000/api/tag/";
File track = new File(Environment.getExternalStorageDirectory(), "mezzo.mp3");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fb = new FileBody(track);
//InputStream inputStream = new ;
//reqEntity.addPart("track", fb);
reqEntity.addBinaryBody("track", track);
final HttpEntity myEntity = reqEntity.build();
httppost.setEntity(myEntity);
Log.i("request", String.valueOf(myEntity));
response = httpclient.execute(httppost);
//process response
responseString = new BasicResponseHandler().handleResponse(response);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null!=response)
{
try
{
HttpEntity httpEntity = response.getEntity();
if (null != httpEntity)
{
httpEntity.consumeContent();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return responseString;
}
protected void onPostExecute(final String responseString) {
runOnUiThread(new Thread() {
public void run() {
Toast.makeText(getApplicationContext(),
responseString, Toast.LENGTH_LONG).show();
}
});
}
What I'm I doing wrong?
I am not sure but I suspect that the http response might not be consumed entirely.
Can you try consuming the response before you return from the function in a finally block:
finally
{
if (null!=response)
{
try
{
HttpEntity httpEntity = response.getEntity();
if (null != httpEntity)
{
httpEntity.consumeContent();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Microsoft ISA Server Authentication in Android

I have an application in Android, in which I were reading files from the remote server, code for reading file is given below;
URI uri = null;
try {
uri = new URI("http://192.168.1.116/Server1/Users.xml");
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("Content-type", "application/json; charset=utf-8");
httpget.setHeader("host", "192.168.1.116");
HttpResponse response = null;
try {
response = httpClient.execute(httpget);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity responseEntity = response.getEntity();
String result = null;
try {
result = EntityUtils.toString(responseEntity);
Log.d("SERVER1", result);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Now all the remote files are behind proxy (Microsoft ISA Server) which required authentication to access the files. Please guide me how I can pass authentication parameters from android to access the files.
I have tried the following codes but useless,
URL uri = null;
try {
uri = new URI("http:// 192.168.1.116/CookieAuth.dll?Logon");
} catch (URISyntaxException e) {
e.printStackTrace();
}
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider()
.setCredentials(
AuthScope.ANY,
new NTCredentials(username, password, deviceIP,
domainName));
HttpPost httppost = new HttpPost(uri);
httppost.setHeader("Content-type",
"application/x-www-form-urlencoded");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("curl", "Z2FServer1/users.xmlZ2F"));
params.add(new BasicNameValuePair("formdir", "3"));
params.add(new BasicNameValuePair("username", "test"));
params.add(new BasicNameValuePair("password", "test"));
UrlEncodedFormEntity ent = null;
try {
ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
httppost.setEntity(ent);
try {
response = httpclient.execute(httppost);
Log.i("Test", response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
Log.d("ISA Server", result);
instream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
But it’s giving HTTP1.1 500 Internal Server Error. I have also tried following link but same error
https://stackoverflow.com/a/10937857/67381
In my case i use
public static DefaultHttpClient getClient(String username, String password,
Integer timeOut) {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, timeOut);
HttpConnectionParams.setSoTimeout(httpParams, timeOut);
DefaultHttpClient retHttpClient = new DefaultHttpClient(httpParams);
if (username != null) {
retHttpClient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(username, password));
}
return retHttpClient;
}
Try, may be works.
P.S.
It's not for ISA, for MS C# WebService Application, but maybe...

Java application terminates at getOutputStream()

I'm creating an application for our Android devices. The aim of this section is to post a username and password (currently just assigned as a string) to a web service and to receive a login token. When running the code, at the getOutputStream() line, my code terminates and will no progress any further.
I have assigned the android emulator GSM access and also set the proxy and DNS server within Eclipse. I'm not sure where to go with it now!
This is within my onHandleIntent():
protected void onHandleIntent(Intent i) {
try{
HttpURLConnection http_conn = (HttpURLConnection) new URL("http://www.XXXXX.com").openConnection();
http_conn.setRequestMethod("POST");
http_conn.setDoInput(true);
http_conn.setDoOutput(true);
http_conn.setRequestProperty("Content-type", "application/json; charset=utf-8");
String login = URLEncoder.encode("XXXXX", "UTF-8") + "=" + URLEncoder.encode("XX", "UTF-8");
login += "&" + URLEncoder.encode("XXXXX", "UTF-8") + "=" + URLEncoder.encode("XX", "UTF-8");
OutputStreamWriter wr = new OutputStreamWriter(http_conn.getOutputStream());
//TERMINATES HERE
wr.write(login);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
String line = rd.toString();
wr.close();
rd.close();
http_conn.disconnect();
}
catch (IOException e){
}
}
This is my first go at java and have only been writing it for a few days so bear with me if I've missed something obvious.
Thanks
If you want to POST something using HTTP, why not use HTTP POST? ;-)
Here is an example snippet:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Source: http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
This may not be the appropriate answer, but will certainly be helpful to you. I have used this code for sending and receiving the request and reply resp, to a webservice.
This code is working, but will need some Refactoring, as i have used some extra variable, which are not needed.
I have used the NameValuePair here for Post
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*
* catch (ParserConfigurationException e) { // TODO
* Auto-generated catch block e.printStackTrace(); } catch
* (SAXException e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
*/
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}
String line = rd.toString();
should be
String line = rd.readLine();
that might do the trick. rd.toString() gives you a String representation of your BufferedReader. It does not trigger the HTTP operation. I did not test your code, so there might be other errors as well, this was just the obvious one.

Categories