//很简单,直接上代码:
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;
}
//-----------------------------------------------------------------------完----------------------------------------------------------------