I am trying to authenticate to a server's secure URL using java.net.urlconnection
- based on the useful tutorial at Using java.net.URLConnection to fire and handle HTTP requests
The response will be as given below--
Return: A session id object: {'session_id': 'username:session_token'}
This session_id
will be used for all methods which require authentication.
This response is JSON response, and I am thinking of using the Google GSON library (since my web app is on Google App Engine).
The code I have used so far (based on the tutorial to which I have given link above) is given below--
String url = "https://api.wordstream.com/authentication/login";
String charset = "UTF-8";
String param1 = WORDSTREAM_API_USERNAME;
String param2 = WORDSTREAM_API_PASSWORD;
// ...
String query = String.format("username=%s&password=%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();
InputStream error = ((HttpURLConnection) connection).getErrorStream();
//now checking HTTP Response status
int status = ((HttpURLConnection) connection).getResponseCode();
How do I proceed further to obtain the JSON response and retrieve session ID from that response correctly?
Another question- I want to store the session ID in session data that can be accessed by javascript functions, because I plan to use javascript functions to make calls and obtain further data. Is this possible, and how to implement this?
Step 1- Create a subclass- declare it as static so that it can be utilised by the GSON library. This subclass should mimic the data contained in a single JSON Response- in our case only the session ID is stored in the response- hence this class contains just one string variable...
static class LR {
public String response;
public LR() {
// No args constructor for LR
}
}
Now, use BUfferedReader and readline to read the entire response and store it in a string variable.
InputStream response = connection.getInputStream();
BufferedReader br = new BufferedReader(new
InputStreamReader(response));
String str="", temp;
while (null != ((temp = br.readLine())))
{
System.out.println (str);
str=str + temp;
}
Finally, invoke 'fromJSON(string, class)' to obtain the value-
Gson gson = new Gson();
LR obj2 = gson.fromJson(str, LR.class);
return(" Session ID="+ obj2.response);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.