I have created a connection in Java to private API
String urlRequest = "https://localhost:8080/orders/create";
String username = "test";
String password = "test";
String certificatePass = "test";
byte[] authEncBytes = Base64.getEncoder().encode((username + ":" + password).getBytes());
URL url = new URL(urlRequest);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
is.close();
After the initial pass, connection seems to remain open, because when running the code from the start, HttpURLConnection throws an Exception at conn.setRequestMethod("POST");,
"Can't reset method: already connected"
I managed to somehow close it now, I don't know what have I done, but does anyone know what the issue here could have been? I restarted my PC in the meantime, and it would still thrown an exception at conn.setRequestMethod("POST");, I don't understand how can a connection persist between restarts. I also tried adding conn.disconnect() before trying to set request method, and that didn't seem to work either. The only thing that made a difference was changing the URL, but I could only connect once, every next time running the code would give me the same exception.
How do I close the connection properly?
Had the issue again today and the problem was with expressions in debug mode. I was calling connect there, I guess while testing so in case anyone didn't know, expressions do affect your variables and can change what's in memory. For instance, having:
int a = 5;
System.out.println(a);
in your code and having a = 6 in your Expressions list, System.out.println(a) will print 6, not 5.
Deleting expressions fixed my problem.
I think your question already has an answer here.
Closing URLConnection and InputStream correctly?
Close your connection at end of the code and don't do it before setRequest method.
Related
I am currently developing an application that needs to interact with the server but i'm having a problem with receiving the data via POST. I'm using Django and then what i'm receiving from the simple view is:
<QueryDict: {u'c\r\nlogin': [u'woo']}>
It should be {'login': 'woooow'}.
The view is just:
def getDataByPost(request):
print '\n\n\n'
print request.POST
return HttpResponse('')
and what i did at the src file on sdk:
URL url = new URL("http://192.168.0.148:8000/data_by_post");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
String parametros = "login=woooow";
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("charset","utf-8");
urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(parametros.getBytes().length));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
writer.write(parametros);
writer.close();
os.close();
I changed the Content-Length to see if that was a problem and then the problem concerning thw value of login was fixed but it was by hard coding (which is not cool).
ps.: everything except the QueryDict is working well.
What could i do to solve this? Am i encoding something wrong at my java code?
thanks!
Just got my problem solved with a few modifications concearning the parameters and also changed some other things.
Having parameters set as:
String parameters = "parameter1=" + URLEncoder.encode("SOMETHING","UTF-8");
then, under an AsyncTask:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
//not using the .setRequestProperty to the length, but this, solves the problem that i've mentioned
conn.setFixedLengthStreamingMode(params.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(params);
out.close();
String response = "";
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
Then, with this, i got the result from django server:
<QueryDict: {u'parameter1': [u'SOMETHING']}>
which is what i was wanting.
I have some working java code which does the following:
URL myUrl = new URL("http://localhost:8080/webservice?user=" + username + "&password=" + password + "&request=x");
HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection();
myConnection.setRequestMethod("POST");
// code continues to read the response stream
However, I noticed that my webserver access log contained the plaintext password for all of the users who connected. I would like to get this out of the access log, but the webserver admins claim that this needs to be changed in my code and not via webserver config.
I tried changing the code to the following:
URL myUrl = new URL("http://localhost:8080/webservice");
HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection();
myConnection.setRequestMethod("POST");
// start of new code
myConnection.setDoOutput(true);
myConnection.addRequestProperty("username", username);
myConnection.addRequestProperty("password", password);
myConnection.addRequestProperty("request", "x");
// code continues to read the response stream
Now the access log does not contain the username/password/request method. However, the webservice now throws an exception indicating that it didn't receive any username/password.
What did I do wrong in my client code? I also tried using "setRequestProperty" instead of "addRequestProperty" and it had the same broken behavior.
I actually found the answer in another question on stackoverflow.
The correct code should be:
URL myUrl = new URL("http://localhost:8080/webservice");
HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(myConnection.getOutputStream ());
wr.writeBytes("username=" + username + "&password="+password + "&request=x");
// code continues to read the response stream
String album = "http://picasaweb.google.com/data/feed/api/user/"+email;
HttpURLConnection con = (HttpURLConnection) new URL(albumUrl).openConnection();
// request method, timeout and headers
con.setRequestMethod("GET") ;
con.setReadTimeout(15000);
con.setRequestProperty("Authorization", "GoogleLogin auth="+auth);
con.setRequestProperty("GData-Version", "2");
// set timeout and that we will process output
con.setReadTimeout(15000);
con.setDoOutput(true);
// connnect to url
con.connect();
// read output returned for url
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Problem : Everytime i call con.getInputStream() it gives me file not found exception.
But when i load the same url in the desktop browser then it is displaying correct data.
I am confused why on android it is throwing exception.
Thanks in advance.
Did you get this? Maybe you just missed the https
below example uses default for authenticated user and the experimental fields list.
url = "https://picasaweb.google.com/data/feed/api/user/default?kind=album&access=public&fields="
+ URLEncoder
.encode("entry(title,id,gphoto:numphotosremaining,gphoto:numphotos,media:group/media:thumbnail)",
"UTF-8");
https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol#ListAlbums
I have java related question...
Website www.stationv3.com gets updated daily (most of the time at least, it's kinda irregular). Every time I connect to a site using address www.stationv3.com (using a browser), it redirects me to it's subpage www.stationv3.com/date_of_latest_update.html
I'm trying to make a program that will pull latest comic from the site, but I am not sure how to find out it's exact address. But I know I'd be able to find out if I could somehow find out where where am I being redirected on every connect. Is that possible with java? I know it can do all sorts of quirky things, but I'm still new to internet related stuff...
I used exact site name just to make it easy for you to check outwhat's going on...
And also, I'm creating a generic code, one which could (with some tinkering) be applyed to any site that functions in that manner.
import java.net.*;
public class ShowStationV3Redirect {
public static void main(String[] args) throws Exception {
URL url = new URL(args[0]);
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
System.out.println("Response code = " + connection.getResponseCode());
String header = connection.getHeaderField("location");
if (header != null)
System.out.println("www.stationv3.com redirected to " + header);
}
}
The above code snippet tells you what URL you are being redirected to.
I think you could just fecth:
http://www.stationv3.com/comics/{yyyy}{mm}{dd}sv3.gif
and forget about the redirection problem. You can use this code (not tested indeed):
URL server = new URL("<put here the image URL>");
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.addRequestProperty("Accept","image/gif");
connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
connection.connect();
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream("c:/mycomic.gif");
byte[] buffer = new byte[1024];
int byteReaded = is.read(buffer);
while(byteReaded != -1)
{
os.write(buffer,0,byteReaded);
byteReaded = is.read(buffer);
}
os.close();
I'm trying to perform webservice calls in android (2.3.4) using the following code snippet. My problem occurs on conn.getOutputStream, as this method seems to be taking a full 20 seconds to return. Any thoughts?
URL uri = new URL(serviceURI + "/remoteMethod");
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
Log.d(TAG, "opening output stream");
OutputStreamWriter writer = new OutputStreamWriter(
conn.getOutputStream());
Log.d(TAG, "output stream opened");
String body = getRequestBody();
writer.write(body);
writer.flush();
writer.close();
int responseCode= conn.getResponseCode();
It would appear that this was probably a network problem, and that jarnbjo was actually correct in his suggestion in the comments that the connection was just taking too long. I moved the server and device to another network (webservice is not public), and the problem cleared up.