I am getting an error
javax.net.ssl.SSLHandshakeException: Connection closed by peer
when i am trying to access a HTTPS url.
my code is:
private void executeHTTRequestVerifyingLogin(String userid, String pwd, String key) throws Exception {
String strReturn = "";
BufferedReader in = null;
HttpClient hc = CUtils.getNewHttpClient();
HttpPost hp = new HttpPost(CGlobalVariables.VERIFYING_LOGIN);
try {
hp.setEntity(new UrlEncodedFormEntity(getNameValuePairs_Login(userid, pwd, key), HTTP.UTF_8));
HttpResponse response = hc.execute(hp);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String data = "";
while ((data = in.readLine()) != null)
sb.append(data);
in.close();
setVerifyingLoginValue(sb.toString());
} catch (Exception e) {
throw e;
}
}
My code is working upto api level 23. I don't know why this exception is thrown in Nougat(Android 7.0) only.
Well the best vote for adding parameters to HttpURLConnection is in this post
But the answer of it is explain about how to adding parameter that have the form something like this
--> "username=usernameValue?password=passwordValue"<--
REMEMBER the parameter can have the form like JSON Object and the answer form the link can make you lost of direction if you dont know about JSON Parameter for POST.
Then this is the best answer from me that i can provide.
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
JSONObject urlParameter = new JSONObject();
urlParameter.put("username", usernameValue);
urlParameter.put("password", passwordValue);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(urlParameter.toString());
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
StringBuilder sb;
sb = new StringBuilder();
if (responseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
} else {
System.out.println(conn.getResponseMessage());
}
String result = sb.toString();
Please enlighten me if you have better solution. TY
I wrote a Java based sign-off routine (token revocation) for an Oauth2 authentication flow. See below the code implementation following the cURL protocol instructions in the manual described [ here ]. The program code compiles and works without error message, but after the log-off the user accounts still remains in a connected state under the WSO2 dashboard query.
See below the Servlet class that triggers the log-off function:
class SignoffServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
try{
String accessToken = (String) req.getSession().getAttribute("access_token");
System.out.println("Start Logoff processing for revoke of the token: " + accessToken);
URL url = new URL (Oauth2Server + "/oauth2/revoke?token="+accessToken);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// new encode with Apache codec (for Java8 use native lib)
String userCredentials = clientId + ":" + clientSecret;
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
connection.setRequestProperty ("Authorization", basicAuth);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.addRequestProperty("token", accessToken);
connection.addRequestProperty("token_type_hint", "access_token");
//connection.setRequestProperty("token", accessToken);
// connection.setRequestProperty("token_type_hint", "access_token");
connection.setRequestMethod("POST");
connection.setDoOutput(true);
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in =
new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
System.out.println("Logoff finished sucessfully");
}
} catch(Exception e) {
System.out.println("Logoff failed, error cause: " + e.toString());
e.printStackTrace();
}
System.out.println("Logoff finished sucessfully");
// return the json of the user's basic info
String html_header = "<html><body>";
String myjson = "<br>Logoff completed sucessfully";
myjson += "<br><br><b><a href='./index.html'>Back to login page</a></b><br>";
String html_footer = "</body></html>";
String mypage = html_header + myjson + html_footer;
resp.setContentType("text/html");
resp.getWriter().println(myjson);
}
}
Advice about what to change in the Java code to activate the sign-off function for Oauth 2.0 is welcome.
Thanks for detailed explanations about the difference between authorization and authentication in Oauth2. See below the code that is able to revoke the valid Oauth2 token:
class SignoffServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
String outputl = "";
try{
String accessToken = (String) req.getSession().getAttribute("access_token");
// testing .. inhibu acivate this line: // revoke accessToken = "abc";
System.out.println("Start Logoff processing for revoke of the token: " + accessToken);
// URL url = new URL (Oauth2Server + "/oauth2/revoke?token="+accessToken);
// URL url = new URL (Oauth2Server + "/oauth2endpoints/revoke");
URL url = new URL (Oauth2Server + "/oauth2/revoke");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
// new encode with Apache codec (for Java8 use native lib)
String userCredentials = clientId + ":" + clientSecret;
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
basicAuth = basicAuth.replace("\\r", "");
basicAuth = basicAuth.replace("\\n", "");
connection.setRequestProperty ("Authorization", basicAuth);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// send data
// String str = "{\"token\": \"" + accessToken + "\",\"token_type_hint\":\"access_token\"}";
// example of JSON string "{\"x\": \"val1\",\"y\":\"val2\"}";
//byte[] outputInBytes = str.getBytes("UTF-8");
//OutputStream os = connection.getOutputStream();
//os.write( outputInBytes );
// os.close();
//send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes("token=" + accessToken);
wr.flush();
wr.close();
// end of new method
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in =
new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
// System.out.println(line); // for debug only
outputl += line;
}
} catch(Exception e) {
System.out.println("Logoff failed, error cause: " + e.toString());
e.printStackTrace();
}
System.out.println("Logoff finished successfully");
// return the json of the user's basic info
// customized Apache HTTP GET with header - Claude, 27 August 2015 reading user information
// ===============================================================================================
String tokeninfo = "";
String infourl = Oauth2Server + "/oauth2/userinfo?schema=openid";
StringBuilder infobody = new StringBuilder();
DefaultHttpClient infohttpclient = new DefaultHttpClient(); // create new httpClient
HttpGet infohttpGet = new HttpGet(infourl); // create new httpGet object
// get some info about the user with the access token
String currentToken = (String) req.getSession().getAttribute("access_token");
String bearer = "Bearer " + currentToken.toString();
infohttpGet.setHeader("Authorization", bearer);
try {
HttpResponse response = infohttpclient.execute(infohttpGet); // execute httpGet
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
System.out.println(statusLine);
infobody.append(statusLine + "\n");
HttpEntity e = response.getEntity();
String entity = EntityUtils.toString(e);
infobody.append(entity);
} else {
infobody.append(statusLine + "\n");
// System.out.println(statusLine);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
tokeninfo = infobody.toString();
infohttpGet.releaseConnection(); // stop connection
}
// User info lookup is done fetching current log status of the token
if (tokeninfo.startsWith("HTTP/1.1 400 Bad Request")) {
tokeninfo = "Token " + currentToken + " was revoked";
};
String html_header = "<html><body>";
String myjson = "<br>Logoff completed successfully";
myjson += "<br>Current Userinfo and Token Status";
myjson += "<br>" + tokeninfo + "<br>";
myjson += "<br><br><b><a href='./index.html'>Back to login page</a></b><br>";
String html_footer = "</body></html>";
String mypage = html_header + myjson + html_footer;
resp.setContentType("text/html");
resp.getWriter().println(myjson);
// to print signoff screen for debug purpose
// resp.getWriter().println(outputl);
}
}
Above doc has been mentioned the way to revoke the access token.Access token revoking and sign-off from OAuth2 authorization server are two different process. As an example; in Facebook, you can revoke the access token which are given for different applications. But it does not mean that you are sign-off from FB or any other application which you already login.
OAuth2 is not an authentication mechanism. It is authorization framework. It does not contain standard way to sign-off from authorization sever. However, there is some custom way which you can use to sign-off (terminate the SSO session in WSO2IS) from WSO2IS which can be used. But, it must be done using the end user's browser (not using the back channel) by calling following url. Please check last part of this for more details
https://localhost:9443/commonauth?commonAuthLogout=true&type=oidc2&sessionDataKey=7fa50562-2d0f-4234-8e39-8a7271b9b273&commonAuthCallerPath=http://localhost:8080/openidconnect/oauth2client&relyingParty=OpenidConnectWebapp
I have a client/server application with which the client is able to upload files to the server and then they are stored in a DB. I followed the instructions found in the following article.
It works fine with files bigger than 1MB, but it doesn't with smallers: the client hangs on getResponseCode().
Here there is my specific client code:
final String UPLOAD_URL = "http://localhost:8080/myApp/myUploadAction"
// takes file path from first program's argument
String filePath = "/home/user/myCSV.csv"
File uploadFile = new File(filePath);
System.out.println("File to upload: " + filePath);
// creates a HTTP connection
URL url = new URL(UPLOAD_URL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
// sets file name as a HTTP header
httpConn.setRequestProperty("fileName", uploadFile.getName());
// opens output stream of the HTTP connection for writing data
OutputStream outputStream = httpConn.getOutputStream()
// Opens input stream of the file for reading data
InputStream inputStream = new FileInputStream(uploadFile);
System.out.println("Start writing data...");
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
println bytesRead
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data was written.");
outputStream.close();
inputStream.close();
// always check HTTP response code from server
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// reads server's response
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String response = reader.readLine();
System.out.println("Server's response: " + response);
} else {
System.out.println("Server returned non-OK code: " + responseCode);
}
Here there is my server side code. The server is based on a Grails application which exposes the following controller to the client:
class UploaderController {
ReportService reportService
def uploadCSV() {
// get CSV file and NPL process name from HTTP header
String fileName = request.getHeader("fileName");
log.info('npl-getcolls-report: received request for ' + nplProcessName + ' - file uploading - ' + fileName)
// prints out all header values (if debug mode is active)
println("===== Begin headers =====")
Enumeration<String> names = request.getHeaderNames()
while (names.hasMoreElements()) {
String headerName = names.nextElement()
println(headerName + " = " + request.getHeader(headerName))
}
println("===== End headers =====\n")
// open input stream of the request for read incoming data
InputStream inputStream = request.getInputStream()
// store CSV into DB
reportService.storeCSV(fileName, inputStream.getBytes())
log.info("data received and stored correctly in DB");
inputStream.close();
def responseData = [
'status': 'OK'
]
render responseData as JSON
}
}
In my program , I read data by using HTTPURLConnection for example
URL url = new URL("https://twitter.com/search?q="+kw+"%20lang%3Aeng%20"+"&src=typd&lang=en");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append("\n");
}
String html = builder.toString();
The problem is only reading data on response page , but I need to read all data that can be retrieved
How I can Load more data in result page