對不起,問你這個問題,但我有點新Java。跨越多個HttpURLConnection請求維護登錄令牌
我有以下類別:
protected class LoginMethod{
public LoginMethod() throws MalformedURLException, UnsupportedEncodingException, IOException{
URL url = new URL("http://example.com/login");
Map<String,Object> params = new LinkedHashMap<>();
params.put("username", user);
params.put("password", password);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
try{
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c = in.read(); c != -1; c = in.read())
token += String.valueOf((char)c);
System.out.println(token);
new LoggedIn();
}catch(IOException es){
System.out.println(es);
}
}
}
這將返回一個JSON字符串的一些標記。 而接下來類:
protected class DoStuff{
public DoStuff() throws MalformedURLException, UnsupportedEncodingException, IOException, ParseException{
JSONParser parser = new JSONParser();
URL url = new URL("http://example.com/DoStuff");
Map<String,Object> params = new LinkedHashMap<>();
params.put("Do", "Stuff");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
try{
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c = in.read(); c != -1; c = in.read())
stuff +=(char)c;
System.out.println(stuff);
new LogOut();
}catch(IOException er){
System.out.println(er);
}
}
}
這將返回DoStuff事情。但是因爲我不知道如何保持這些類之間的會話,所以我得到了401錯誤。 我的問題是如何保持這些類之間的會話或提示如何將它們放入支持會話的單個類中,記住它們由單獨的按鈕調用。 謝謝!