我有以下 cURL 请求
curl -i --data 'user=user1&password=password1' -X POST http://127.0.0.1:8080/login
这会返回以下响应:
HTTP/1.1 200 OK
Access-Control-Allow-Origin:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: authorization,Content-Type
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, HEAD, DELETE
Date: Monday, January 22, 2017 10:07:22 AM UTC
Set-Cookie: JSESSIONID=XXXYYYZZZ; Path=/; HttpOnly
Content-Type: application/json
Content-Length: 118
Server: Jetty(9.2.15.v20160210)
{"status":"OK","message":"","body":{"principal":"user1","ticket":"el23-esedejhz943"}}
我想用 Java 进行此调用,并提取 Set-Cookie 字段中的 JSESSIONID。我怎样才能做到这一点?
最佳答案
一种不使用任何外部库的方法,适用于 http,但不适用于 https(因为证书 - 这可以设置为工作,但对于这篇文章来说太宽泛了)
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JsessionIdExtractor {
public static void main(String[] args) throws Exception {
String jSessionId = logInAndRetrieveJsessionId();
System.out.println("JSESSIONID is: " + jSessionId);
}
private static String logInAndRetrieveJsessionId() throws Exception {
String url = "http://127.0.0.1:8080/login";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Some browser name eg. fierfox");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String postParameters = "user=user1&password=password1";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParameters);
System.out.println("Response Code : " + responseCode);
return extractJsessionId(con);
}
private static String extractJsessionId(HttpURLConnection con) {
Map<String, List<String>> headerFields = con.getHeaderFields();
Set<String> headerFieldsSet = headerFields.keySet();
Iterator<String> hearerFieldsIter = headerFieldsSet.iterator();
while (hearerFieldsIter.hasNext()) {
String headerFieldKey = hearerFieldsIter.next();
if ("Set-Cookie".equalsIgnoreCase(headerFieldKey)) {
List<String> headerFieldValue = headerFields.get(headerFieldKey);
for (String headerValue : headerFieldValue) {
System.out.println("Cookie Found...");
String[] fields = headerValue.split(";\\s*");
String cookieValue = fields[0];
if (cookieValue.toUpperCase().trim().startsWith("JSESSIONID")) {
return cookieValue.split("=")[1];
}
}
}
}
throw new RuntimeException("there is no JSESSIONID cookie in reponse");
}
}
关于java - 如何从 Java 中的 post 请求中提取 httponly cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41820314/