This question already has answers here:
"java.net.MalformedURLException: Protocol not found" read to html file
(2 answers)
Closed 9 years ago.
I am using following code and it keeps giving me malformedurlexception error. The funny part is I have copied it from another project which the same code is working properly. I was wondering if anyone can see what the problem might be. The section of code which is giving the error is in OpenHttpConnection function and at start where it says:
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
I appreciate any help I can get.
Bitmap bitmapOrg = null;
bitmapOrg = DownloadImage("http://www.bagherpour.com/apache_pb.gif");
public Bitmap DownloadImage(String txt)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(txt);
bitmap = BitmapFactory.decodeStream(in);
in.close();
return bitmap;
} catch (IOException e1) {
e1.printStackTrace();
Log.d("bitMap",e1.toString());
return null;
}
}
public InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
Change to:
URL rul = new URL("httpwww.bagherpour.com/apache_pb.gif")
Related
I am trying to download a file through code and it is working if the file is found. But if the Link returns a 302 code, I am getting a connection timeout through code. It is working fine in browser.
Can someone help me out where I am going wrong?
My code is given below:
private static void downloadFile(String fileUrl, String fileName) {
HttpURLConnection connection = null;
try {
URL url = new URL(fileUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.connect();
int code = connection.getResponseCode();
String message = connection.getResponseMessage();
System.out.println(code + "-" + message);
if (code == HttpURLConnection.HTTP_OK) {
try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream fileOutputStream = new FileOutputStream(fileName)) {
byte dataBuffer[] = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
throw new Exception("Invalid Response Code: " + code + ", Response Message: " + message);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Working URL(200): https://archives.nseindia.com/content/historical/DERIVATIVES/2022/SEP/fo16SEP2022bhav.csv.zip
Timeout URL(302): https://archives.nseindia.com/content/historical/DERIVATIVES/2022/SEP/fo17SEP2022bhav.csv.zip
A setting
connection.setInstanceFollowRedirects(true); // follow response codes 3xx
connection = (HttpURLConnection) new URL(fileUrl).openConnection();
connection.setInstanceFollowRedirects(true); // follow response codes 3xx
connection.setRequestMethod("GET");
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.connect();
How to call subsequent requests using j_security_check, I have followed below code but it's not working .
String url = "https://myhost/jsp/j_security_check?j_username=myuser&j_password=mypassword";
HttpURLConnection connection = (HttpURLConnection) new
URL(url).openConnection();
if (connection.getResponseCode() == 200) {
String cookie = connection.getHeaderField("Set-Cookie").split(";", 2)[0];
url = "https://myhost/getusers";
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Cookie", cookie);
connection.setRequestProperty("Cache-Control", "no-cache");
InputStream input = connection.getInputStream();
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String result = buffer.lines().collect(Collectors.joining("\n"));
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
Can anyone help me on it.
I'm trying to make a simple function that grabs an image from an http connection. It was working before, now it's throwing some errors. I didn't make any changes to the code. Also the Input stream isn't null. It's returning expected data.
D/skia: ---- read threw an exception
D/skia: --- SkAndroidCodec::NewFromStream returned null
I/ERROR: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
This is my Code for reference inside of an async task:
#Override
protected Bitmap doInBackground(String... url){
try {
InputStream in = openHttpConnection(url[0]);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
return bitmap;
} catch (IOException e) {
Log.i("ERROR", e.toString());
return null;
}
}
private static InputStream openHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
httpConn.disconnect();
} catch (Exception e) {
Log.i("ERROR", e.toString());
throw new IOException("Error connecting");
}
return in;
}
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
After this statement bitmap is null. It will always be if you ask decodeStream to just decode the bounds.
Later you try to compress that null bitmap with `bitmap.Compress().
It does not matter if that would be in a static function.
Just dont call it if bitmap==null.
I have created web service call using java below code. Now I need to make delete and put operations to be perform.
URL url = new URL("http://example.com/questions");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod( "POST" );
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(jsonBody.getBytes());
os.flush();
When I add below code to perform DELETE action it gives errors saying:
java.net.ProtocolException: HTTP method DELETE doesn't support output.
conn.setRequestMethod( "DELETE" );
So how to perform delete and put requests?
PUT example using HttpURLConnection:
URL url = null;
try {
url = new URL("http://localhost:8080/putservice");
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("PUT");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.write("hello");
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
if (httpsURLConnection != null) {
httpsURLConnection.disconnect();
}
}
DELETE example using HttpURLConnection:
URL url = null;
try {
url = new URL("http://localhost:8080/deleteservice");
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("DELETE");
System.out.println(httpURLConnection.getResponseCode());
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
FOR PUT
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();
FOR DELETE
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();
Actually got it from the link here:
Send PUT, DELETE HTTP request in HttpURLConnection
i suggest you to use restlet client for web service request .please refer the bellow sample code ,it may help you
Client client = new Client(new Context(), Protocol.HTTP);
clientResource = new ClientResource(url);
ResponseRepresentation responseRep = null;
try {
clientResource.setNext(client);
clientResource.delete();
} catch (Exception e) {
e.printStackTrace();
}
I've already looked through resources which describe specifics of work with HttpURLConnection as in Java so in Android (where there is not default implementation of working with connection pool) and my question is: if I close a stream gotten from HttpURLConnection, will the system create a new one Socket at a next time when I establish a HttpURLConnection with the same URL or it will try to use an exist one? Considering the following code:
private byte[] downloadText(URL url, String data) {
OutputStream out = null;
InputStream in = null;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
conn.setRequestMethod("POST");
conn.setReadTimeout(20 * 1000);
conn.setConnectTimeout(15 * 000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
byte[] payload = data.getBytes("utf-8");
conn.setFixedLengthStreamingMode(payload.length);
conn.connect();
out = new BufferedOutputStream(conn.getOutputStream());
out.write(payload);
out.flush();
final int responseCode = conn.getResponseCode();
final String responseMessage = conn.getResponseMessage();
is = conn.getInputStream();
if((responseCode / 100) == 2 || responseMessage.equals("OK")) {
return readFromStream(is);
}
} catch (IOException e) {
Log.e(TAG, "Error occurred while trying to connect to the server" + e.toString());
} finally {
try {
if(out != null) {
out.close();
}
if(is != null) {
is.close();
}
} catch(IOException e) {
Log.e(TAG, "Error occurred while trying to close data streams" + e.toString());
}
}
}
Your question doesn't make sense. If there isn't a connection pool, there is no 'existing socket' to reuse.