通过 httpurlconnection 更改 HttpPost
change HttpPost by httpurlconnection
我有一种方法可以将一些数据发送到服务器并获得一个 cookie response.this 是我的方法:
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 return 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
使用改装。
您将使用注释来描述 HTTP 请求,URL默认集成了参数替换和查询参数支持。此外,它还提供自定义 headers、多部分请求 body、文件上传和下载、模拟响应等功能。在后面的教程中,我们将更详细地研究所有这些。
https://futurestud.io/tutorials/retrofit-getting-started-and-android-client
用这个,希望有用。
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
String s = "yourJsonName =" json.toString();
writer.write(s);
writer.flush();
writer.close();
要获取 cookie 并在下一个请求中再次发送它,您可以这样做:
SharedPreferences preferences = this.getSharedPreferences("CommonPrefs",
Activity.MODE_PRIVATE);
if (!preferences.getString("cookieName", "no_cookie").equals("no_cookie")) {
connection.setRequestProperty("Cookie", preferences.getString("cookieName", "no_cookie"));
}
for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
SharedPreferences.Editor editor = preferences.edit();
if (headerName.equals("Set-Cookie")) {
String cookie = connection.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
editor.putString("cookieName", cookie);
editor.apply();
break;
}
editor.putString("cookieName", "no_cookie");
}
connection.connect();
为了从 inputStream 中获取 json,我强烈建议您使用 Gson,如下所示:
private ArrayList<YourClassOfObject> readJson(InputStream is) throws IOException {
ArrayList<YourClassOfObject> c = new ArrayList<>();
try{
Reader reader = new InputStreamReader(is , "UTF-8");
Gson gson = new Gson();
YourClassOfObject[] p;
p = gson.fromJson(reader, YourClassOfObject[].class);
c.addAll(Arrays.asList(p));
}catch (IOException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}catch (ExceptionInInitializerError e){
e.printStackTrace();
}
return c;
}
我有一种方法可以将一些数据发送到服务器并获得一个 cookie response.this 是我的方法:
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 return 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
使用改装。
您将使用注释来描述 HTTP 请求,URL默认集成了参数替换和查询参数支持。此外,它还提供自定义 headers、多部分请求 body、文件上传和下载、模拟响应等功能。在后面的教程中,我们将更详细地研究所有这些。
https://futurestud.io/tutorials/retrofit-getting-started-and-android-client
用这个,希望有用。
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
String s = "yourJsonName =" json.toString();
writer.write(s);
writer.flush();
writer.close();
要获取 cookie 并在下一个请求中再次发送它,您可以这样做:
SharedPreferences preferences = this.getSharedPreferences("CommonPrefs",
Activity.MODE_PRIVATE);
if (!preferences.getString("cookieName", "no_cookie").equals("no_cookie")) {
connection.setRequestProperty("Cookie", preferences.getString("cookieName", "no_cookie"));
}
for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
SharedPreferences.Editor editor = preferences.edit();
if (headerName.equals("Set-Cookie")) {
String cookie = connection.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
editor.putString("cookieName", cookie);
editor.apply();
break;
}
editor.putString("cookieName", "no_cookie");
}
connection.connect();
为了从 inputStream 中获取 json,我强烈建议您使用 Gson,如下所示:
private ArrayList<YourClassOfObject> readJson(InputStream is) throws IOException {
ArrayList<YourClassOfObject> c = new ArrayList<>();
try{
Reader reader = new InputStreamReader(is , "UTF-8");
Gson gson = new Gson();
YourClassOfObject[] p;
p = gson.fromJson(reader, YourClassOfObject[].class);
c.addAll(Arrays.asList(p));
}catch (IOException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}catch (ExceptionInInitializerError e){
e.printStackTrace();
}
return c;
}