//很簡單,直接上代碼:
public String post(String httpsUrl, String params) {
String result = null;
try {
URL url = new URL(httpsUrl); // 解析httpsUrl,生成url對象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.connect();
conn.getOutputStream().write(params.getBytes());
conn.getOutputStream().flush();
conn.getOutputStream().close();
Log.e("TAG", "ResponseCode=" + conn.getResponseCode());
if (conn.getResponseCode() == 200) {
InputStream input = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
result = bufferedReader.readLine();
input.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
//在點擊事件裏調用:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.mButton:
//這個data是自己拼接的表單,根據自己的需要
final String data = "grant_type=password" + "&username=9371***" + "&password=***" + "&client_secret=server" + "&client_id=server" + "&scope=server";
new Thread(new Runnable() {
@Override
public void run() {
String post = post("這裏放你的url", data);
Log.e("TAG", post + "");
}
}).start();
break;
}
}
//簡單的請求就完成了,下面是我的升級版的,加了一些請求返回值成功或者失敗的判斷,錯誤的判斷:
//發起網絡請求
public String jsonPost(final String path, final String string) {
String result = "";
OutputStream os = null;
try {
URL url = new URL(path);
// 然後我們使用httpPost的方式把lientKey封裝成Json數據的形式傳遞給服務器
// 在這裏呢我們要封裝的時這樣的數據
// 我們把JSON數據轉換成String類型使用輸出流向服務器寫
// 現在呢我們已經封裝好了數據,接着呢我們要把封裝好的數據傳遞過去
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
// 設置允許輸出
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
os = conn.getOutputStream();
os.write(string.getBytes());
os.flush();
// 定義BufferedReader輸入流來讀取URL的響應
Log.e("TAGH1", conn.getResponseCode() + "");
if (conn.getResponseCode() == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
result = bufferedReader.readLine();
}
} catch (SocketTimeoutException e) {
// Log.i("錯誤", "連接時間超時");
e.printStackTrace();
return "錯誤";
} catch (MalformedURLException e) {
// Log.i("錯誤", "jdkfa");
e.printStackTrace();
return "錯誤";
} catch (ProtocolException e) {
// Log.i("錯誤", "jdkfa");
e.printStackTrace();
return "錯誤";
} catch (IOException e) {
// Log.i("錯誤", "jdkfa");
e.printStackTrace();
return "錯誤";
}// 使用finally塊來關閉輸出流、輸入流
finally {
try {
if (os != null) {
os.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
//在點擊事件裏調用:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.mButton:
//這個data是自己拼接的表單,根據自己的需要
final String data = "grant_type=password" + "&username=9371***" + "&password=***" + "&client_secret=server" + "&client_id=server" + "&scope=server";
new Thread(new Runnable() {
@Override
public void run() {
String s = jsonPost("這裏放你的url", data);
Log.e("TAG", s + "");
}
}).start();
break;
}
}
//簡潔版 直接返回成功的信息或錯誤的信息:
/*
* 方法名:jsonPost(final String path, final JSONObject json)
* 功 能:發起網絡請求,form提交
* 參 數:String path, String string
* 返回值:String
*/
public String jsonPost(final String path, final String string) throws IOException {
String result = "";
OutputStream os = null;
URL url = null;
HttpURLConnection conn = null;
url = new URL(path);
// 然後我們使用httpPost的方式把lientKey封裝成Json數據的形式傳遞給服務器
// 在這裏呢我們要封裝的時這樣的數據
// 我們把JSON數據轉換成String類型使用輸出流向服務器寫
// 現在呢我們已經封裝好了數據,接着呢我們要把封裝好的數據傳遞過去
conn = (HttpURLConnection) url.openConnection();
// conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //設置請求體的類型是文本類型
// 設置通用的請求屬性
// conn.setRequestProperty("accept", "*/*");
// conn.setRequestProperty("connection", "Keep-Alive");
// conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setConnectTimeout(5000);//設置連接超時
conn.setReadTimeout(5000);//設定讀取超時
conn.setDoInput(true);//設置允許輸入
conn.setDoOutput(true);//設置允許輸出
conn.setRequestMethod("POST");//設置請求方式
conn.setUseCaches(false);//設置緩存
os = conn.getOutputStream(); //獲得輸出流,向服務器寫入數據
conn.setConnectTimeout(5000);//設置連接超時
conn.setReadTimeout(5000);//設定讀取超時
conn.setDoInput(true);//設置允許輸入
conn.setDoOutput(true);//設置允許輸出
conn.setRequestMethod("POST");//設置請求方式
conn.setUseCaches(false);//設置緩存
os = conn.getOutputStream();
os.write(string.getBytes());
os.flush();
// 定義BufferedReader輸入流來讀取URL的響應
Log.i("LoginActivity", "登錄ResponseCode:" + conn.getResponseCode());
if (conn.getResponseCode() == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
result = bufferedReader.readLine();
} else {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
result = bufferedReader.readLine();
}
if (os != null) {
os.close();
}
Log.i("LoginActivity", "請求Token返回信息:" + result);
return result;
}
//拼接參數 表單請求,解決WIFI無法使用,重定向:
/**
* 方法名:jsonPost(final String path, final JSONObject json)
* 功 能:拼接請求參數,發起網絡請求,form提交
* 參 數:String path, String uid, String pwd
* 返回值:String
*/
public static String jsonPost(final String path, String uid, String pwd) {
LinkedHashMap<String, String> params = new LinkedHashMap<>();
params.put("grant_type", "password");
params.put("username", uid);
params.put("password", Md5.MD5(pwd));
params.put("client_secret", "server");
params.put("client_id", "server");
params.put("scope", "server");
// 拼接請求參數
StringBuffer buffer = new StringBuffer();
for (Map.Entry<String, String> entry : params.entrySet()) {
buffer.append(entry.getKey());
buffer.append('=');
buffer.append(entry.getValue());
buffer.append('&');
}
buffer.deleteCharAt(buffer.length() - 1);
final String data = buffer.toString();
XLog.i("AuthUtil", "獲取Token地址:" + path + " 獲取Token參數:" + data);
XLog.i("AuthUtil", "獲取Token 密碼MD5:" + Md5.MD5(Global.userInfo.getPwds()));
String result = "";
OutputStream os = null;
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
// conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //設置請求體的類型是文本類型
// 設置通用的請求屬性
// conn.setRequestProperty("accept", "*/*");
// conn.setRequestProperty("connection", "Keep-Alive");
// conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setConnectTimeout(5000);//設置連接超時
conn.setReadTimeout(5000);//設定讀取超時
conn.setDoInput(true);//設置允許輸入
conn.setDoOutput(true);//設置允許輸出
conn.setRequestMethod("POST");//設置請求方式
conn.setUseCaches(false);//設置緩存
os = conn.getOutputStream(); //獲得輸出流,向服務器寫入數據
os.write(data.getBytes());
os.flush();
//定義BufferedReader輸入流來讀取URL的響應
XLog.i("AuthUtil", "請求Token ResponseCode:" + conn.getResponseCode());
if (conn.getResponseCode() == 200) {
XLog.i("AuthUtil", "請求Token返回成功信息:" + result);
if (!url.getHost().equals(conn.getURL().getHost())) { //連接被重定向了!需要指引用戶去登錄WiFi
return "當前WIFI無法使用,需要認證!";
} else {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
result = bufferedReader.readLine();
}
} else if (conn.getResponseCode() == 400) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
result = bufferedReader.readLine();
XLog.e("AuthUtil", "請求Token返回錯誤信息:" + result);
try {
JSONObject jsonObject = new JSONObject(result);
String message = jsonObject.optString("message");
return message;
} catch (JSONException e) {
e.printStackTrace();
XLog.e("AuthUtil", "請求Token返回錯誤信息:" + e.toString());
}
} else {
XLog.e("AuthUtil", "請求Token返回錯誤信息:" + conn.getResponseCode());
return "服務器內部錯誤";
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
XLog.e("AuthUtil", "請求Token返回錯誤信息:" + e.toString());
}
return result;
}
//-----------------------------------------------------------------------完----------------------------------------------------------------