Doing GET request with URLConnection. code is here
java.net.URL url = new java.net.URL(requestUrl);
URLConnection urlConnection = url.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
getting java.io.FileNotFoundException whereas requested url is correct. i think it may be https ssl certificate issue. if anyone else got this issue and resolved please update.
Encode your parameter to create an URL for request.Unsupported
character in parameter value may cause to exceptions it can be a white space also.
String url = "http://url.com";
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String param1 = "value1";
String param2 = "value2";
// ...
String query = String.format("param1=%s¶m2=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...
Courtsey
Related
I have a problem on HttpURLConnection in post method. Everything is working fine on get method however, when I try to use Post method. I'm getting this error message.
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL
Here's my code snippet. I hope you could help me about this.
URL url = new URL(my url/userInfo);
String encoding = Base64.getEncoder().encodeToString(("username:password").getBytes("UTF-8"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("x-csrf-token", "fetch");
String csrfToken = connection.getHeaderField("x-csrf-token");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
String output = in.readLine();
in.close();
String content = data // expected data to retrieve
URL url2 = new URL(my URL);//another url to push the data retrieve
HttpURLConnection connection2 = (HttpsURLConnection) url2.openConnection();
connection2.setDoInput(true);
connection2.setDoOutput(true);
connection2.setRequestMethod("POST");
connection2.setRequestProperty("Authorization", "Basic " + encoding);
connection2.setRequestProperty("Accept", "application/json");
connection2.setRequestProperty("x-CSRFToken", csrfToken);
connection2.setRequestProperty("cache-control", "no-cache");
OutputStream os = connection2.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(data);//this is where the data will be pushed
osw.flush();
osw.close();
os.close();
the idea is, we need first to get the x-csrf-token and data from the first link, which is okay. After GET Method execution, the POST method will occur. unfortunately, the post method is not working. I'm getting the error message shown above. By the way, we tried to do a post method in POSTMAN and it' working fine.
Hoping you could help me about this.
I need to fetch content from third party web application UI but after login, site redirects to many pages. I am not understanding how to retrieve data from last opened page.
Presently I am receiving in.readLine() method returns null if I use "OPTIONS" instead of GET.
If I use GET then error 405.
Rest Client shows the connection success through GET method and also redirecting it to desired page.
Please suggest.
I connected to url through URLConnection
HttpsURLConnection con = (HttpsURLConnection) new URL("https://***.com/MRcgi/MRhomepage.pl" + "?" + query).openConnection();
Complete code is as follows-
String charset = "UTF-8"; // Or in Java 7 and later, use the constant:
String USER = "*****";
String PROJECTID = "1";
String MRP = "1eba539717f66151f557b49fd7e8a8d28";//dynamically changes
String OPTION = "none";
String WRITECACHE = "1";
String FIRST_TIME_IN_FP = "1";
String FIRST_TIME_IN_PROJ = "1";
String dispatch_script = "MRlogin.pl";
String query = String
.format("USER=%s&PROJECTID=%s&MRP=%s&OPTION=%s&WRITECACHE=%s&FIRST_TIME_IN_FP=%s&FIRST_TIME_IN_PROJ=%s&dispatch_script=%s&",
URLEncoder.encode(USER, charset),
URLEncoder.encode(PROJECTID, charset),
URLEncoder.encode(MRP, charset),
URLEncoder.encode(OPTION, charset),
URLEncoder.encode(WRITECACHE, charset),
URLEncoder.encode(FIRST_TIME_IN_FP, charset),
URLEncoder.encode(FIRST_TIME_IN_PROJ, charset),
URLEncoder.encode(dispatch_script, charset));
HttpsURLConnection con = (HttpsURLConnection) new URL(
"https://***com/MRcgi/MRhomepage.pl" + "?" + query)
.openConnection();
String userPassword = "domain\\user:password";
String encoding = new String(
org.apache.commons.codec.binary.Base64
.encodeBase64(org.apache.commons.codec.binary.StringUtils
.getBytesUtf8(userPassword)));
System.out.println("----" + encoding);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "text/plain");
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty("Authorization", "Basic " + encoding);
USER=user&MRP=15c6ca083c2f75a73e0fbbd2832290f29&PROJECTID=1&USECACHEURL=1&IGNORE_REAL_ACTIVE_TIME=1";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
//wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
System.out.println("-----" + in.readLine());
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
setDoOutput(true) is used for POST and PUT requests. If it is false then it is for using GET requests.
Its not required in my code, so I simply commented setDoOutput(true), and request went as GET
Also below url helped me a lot in understanding it-
What exactly does URLConnection.setDoOutput() affect?
I searched other topics and there were some answers but I didn't succeed to solve my problem.
I have this code and I want to add "Referer" to my http headers.
After using setRequestProperty method, I log the results in Logcat but I don't see referer in the output. what am I doing wrong?
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Referer", "http://www.example.com");
for(int i=0;con.getHeaderFieldKey(i)!=null;i++){
String headerName = con.getHeaderFieldKey(i);
String headerValue = con.getHeaderField(i);
Log.d("Header", headerName + ": " + headerValue);
}
I also have another code which is not working either:
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
String IRNIC = cookies.get("IRNIC");
String ROUTEID = cookies.get("ROUTEID");
String myCookies = "IRNIC="+IRNIC+"; ROUTEID="+ROUTEID;
con.setRequestProperty("Cookie", myCookies);
for(int i=0;con.getHeaderFieldKey(i)!=null;i++){
String headerName = con.getHeaderFieldKey(i);
String headerValue = con.getHeaderField(i);
Log.d("Header", headerName + ": " + headerValue);
}
For the first code, I don't see referer in the output and also for the second code, I don't see cookies too.
So it seems setRequestProperty is not working!
Thanks in advance.
EDIT: I can see headers in the output but not the ones I added via setRequestProperty method. so the if code is working.
From docs:
getHeaderFields
Returns an unmodifiable map of the response-header fields and values
setRequestProperty
Sets the value of the specified request header field.
Request is not the same as response. That's why your headers are different. The request will have correct headers using setRequestProperty
i have to retrive a csv using https protocol and Basic Authentication in java. i used this code but the output stream retrived is an array with 250 zero. there are some error in my code?
String webPage = url_a;
String name = email;
String password = pass;
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL url = new URL(webPage);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.addRequestProperty("Authorization", "Basic " + authStringEnc);
urlConnection.setRequestMethod("POST");
urlConnection.setAllowUserInteraction(false);
urlConnection.setDoInput(false);
urlConnection.setDoOutput(true);
urlConnection.connect();
final OutputStream outs = urlConnection.getOutputStream();
If you're trying to read the response, try urlConnection.getInputStrem() ...
The names input/output are viewed from your point of view (as client). So output is what you send out to server, and input is what you receive from server.
Hi in my android project i m calling a webservice and sending get parameter through query string parameter , now problem is that if query string parameter value contains any white space then i am getting 505 error
URL url = new URL(urlstring.trim());
urlConnection = (HttpURLConnection) url.openConnection();
int response = urlConnection.getResponseCode();
I have one doubt if i use URLEncode(urlstring.trim(),"UTF-8")do i need to change my webservice code also ?
You should encode only the values of your params:
String urlString = "http://test.com?param1=" + URLEncoder.encode(value1, "UTF-8") + "¶m2=" + URLEncoder.encode(value2, "UTF-8") ;
URL url = new URL(urlstring.trim());
urlConnection = (HttpURLConnection) url.openConnection();
int response = urlConnection.getResponseCode();