【发布时间】:2018-01-06 23:55:43
【问题描述】:
我有一个方法可以向服务器发送一些数据并得到一个 cookie 响应。这是我的方法:
public Cookie getCookie(String username, String password) {
try {
JSONObject obj = new JSONObject();
key = UUID.randomUUID().toString();
userEncrypt = .....
passwordEncrypt = ......
obj.put("username", userEncrypt);
obj.put("password", passwordEncrypt);
obj.put("customCredential", key + ",Mobile" + deviceId);
obj.put("isPersistent", false);
HttpPost request = new HttpPost(AppUtil.getConfig(baseActivity, App.SERVICE_AUTH) + "Login");
request.setHeader("Content-Type", "application/json; charset=utf-8");
request.setEntity(new StringEntity(obj.toString(), "utf-8"));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
if (result.toLowerCase(Locale.US).equals("true")) {
for (Cookie cookie : client.getCookieStore().getCookies()) {
if (cookie.getName().contains(".ASPXAUTH"))
return cookie;
}
}
我想使用 httpurlconnection 但我不知道如何更改它?如何通过 httpurlconnection 返回 cookie?
这是我写的新方法:
String result = "";
HttpURLConnection connection = null;
connection = (HttpURLConnection) new URL(AppUtil.getConfig(this, App.SERVICE_AUTH) + "Login").openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
OutputStream os = connection.getOutputStream();
os.write((obj.toString()).getBytes("UTF-8"));
os.flush();
int responseCode = connection.getResponseCode();
我在 responseCode 上得到 400。有人可以帮忙吗?thnx
【问题讨论】:
标签: android httpclient httpurlconnection