Android에서 쿠키를 사용하여 http 요청을 하려면 어떻게 해야 하나요?
쿠키를 적절하게 처리하면서 원격 서버에 http 요청을 하고 싶습니다(예: 서버에서 보낸 쿠키를 저장하고 이후 요청을 할 때 해당 쿠키를 보냅니다).모든 쿠키를 보존하는 것은 좋지만, 내가 신경 쓰는 것은 세션 쿠키뿐입니다.
java.net 에서는 java.net 를 사용하는 것이 바람직하다고 생각됩니다.Cookie Handler(기본 클래스 참조) 및 java.net.Cookie Manager(구체적인 구현).Android에는 java.net가 있습니다.Cookie Handler는 java.net이 없는 것 같습니다.Cookie Manager 。
http 헤더를 조사함으로써 모든 것을 수작업으로 코드화할 수 있지만, 더 쉬운 방법이 있을 것 같습니다.
쿠키를 유지하면서 Android에서 http 요청을 하는 올바른 방법은 무엇입니까?
Google Android에는 Apache HttpClient 4.0이 포함되어 있으며, HttpClient 문서의 "양식 기반 로그온" 예를 사용하여 이 작업을 수행하는 방법을 파악할 수 있었습니다.
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class ClientFormLogin {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
"org=self_registered_users&" +
"goto=/portal/dt&" +
"gotoOnFail=/portal/dt?error=true");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
cookie는 다른 HTTP 헤더에 불과합니다.아파치 라이브러리 또는 HTTP Url Connection을 사용하여 HTTP 콜을 발신할 때 언제든지 설정할 수 있습니다.어느 쪽이든 HTTP 쿠키를 이 방법으로 읽고 설정할 수 있어야 합니다.
당신이 얼마나 쉽게 만들 수 있는지 보여줄 수 있는 안전한 코드를 공유할 수 있습니다.
public static String getServerResponseByHttpGet(String url, String token) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
get.setHeader("Cookie", "PHPSESSID=" + token + ";");
Log.d(TAG, "Try to open => " + url);
HttpResponse httpResponse = client.execute(get);
int connectionStatusCode = httpResponse.getStatusLine().getStatusCode();
Log.d(TAG, "Connection code: " + connectionStatusCode + " for request: " + url);
HttpEntity entity = httpResponse.getEntity();
String serverResponse = EntityUtils.toString(entity);
Log.d(TAG, "Server response for request " + url + " => " + serverResponse);
if(!isStatusOk(connectionStatusCode))
return null;
return serverResponse;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Apache 라이브러리는 더 이상 사용되지 않으므로 사용하려는 사용자에게는HttpURLConncetion
다음 답변의 도움을 받아 Get and Post Request를 전송하기 위해 이 클래스를 작성했습니다.
public class WebService {
static final String COOKIES_HEADER = "Set-Cookie";
static final String COOKIE = "Cookie";
static CookieManager msCookieManager = new CookieManager();
private static int responseCode;
public static String sendPost(String requestURL, String urlParameters) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
//While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
conn.setRequestProperty(COOKIE ,
TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
}
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
if (urlParameters != null) {
writer.write(urlParameters);
}
writer.flush();
writer.close();
os.close();
Map<String, List<String>> headerFields = conn.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
}
}
setResponseCode(conn.getResponseCode());
if (getResponseCode() == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
// HTTP GET request
public static String sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla");
/*
* https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
* Get Cookies form cookieManager and load them to connection:
*/
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
//While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
con.setRequestProperty(COOKIE ,
TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
}
/*
* https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
* Get Cookies form response header and load them to cookieManager:
*/
Map<String, List<String>> headerFields = con.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
}
}
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
public static void setResponseCode(int responseCode) {
WebService.responseCode = responseCode;
Log.i("Milad", "responseCode" + responseCode);
}
public static int getResponseCode() {
return responseCode;
}
}
저는 구글 안드로이드를 사용하고 있지 않지만, 이 작업을 수행하는 것은 그다지 어렵지 않다고 생각합니다.Java 튜토리얼의 관련 비트를 읽으면 등록된 쿠키 핸들러가 HTTP 코드로부터 콜백을 받는 것을 볼 수 있습니다.
그래서가 없으면 기본(만약디폴트값이 없는 경우(확인하셨나요 당신은 보고를 했습니까?) 있다.CookieHandler.getDefault()
정말?)그때 당신이 가서 put/get을 이행하고 거의 자동으로 일하게 하CookieHandler를 연장할 수 있어가 null입니다.쿠키 Handler를 확장하여 put/get을 구현하고 자동으로수 있습니다 작동시킬거의.만약 당신이 그 길로 가동시 접속과 같은 것을 고려해야 한다.그 루트로 갈 경우 동시접속 등을 고려하시기 바랍니다.
Edit:분명히 당신은 기본 처리기 통해 사용자 지정 구현의 인스턴스를 설정할 수도 있겠군요.CookieHandler.setDefault()
콜백을 받기 위해.잊어 버린 그 일을 제기하는 것.
언급URL : https://stackoverflow.com/questions/678630/how-do-i-make-an-http-request-using-cookies-on-android
'programing' 카테고리의 다른 글
PHP 코드에서 assert를 사용해야 합니까? (0) | 2022.09.18 |
---|---|
자바에서는 작은따옴표와 큰따옴표가 다른가요? (0) | 2022.09.18 |
JavaScript 개인 메서드 (0) | 2022.09.18 |
다른 구성요소에서 지도 도면층 가시성 전환 (0) | 2022.08.28 |
문자열을 플로트로 변환하는 방법 (0) | 2022.08.28 |