工具类直接用就行:
import android.os.Handler;
import android.os.Message;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Post请求
*/
public class PostUtil {
//新线程调用请求方法(安卓不允许主线程进行网络请求)
public static void postrun(String url, String param,Handler handler){//第一个参数url,2是传入的值
new Thread(new Runnable(){
@Override
public void run() {
try {
Message message=new Message();
message.obj = postMethod(url,param);
handler.sendMessage(message);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
//请求方法
public static JSONObject postMethod(String url,String param){
// 结果值
StringBuffer rest=new StringBuffer();
HttpURLConnection conn=null;
OutputStream out=null;
BufferedReader br=null;
JSONObject jsonObject=null;
try {
// 创建 URL
URL restUrl = new URL(url);
// 打开连接
conn= (HttpURLConnection) restUrl.openConnection();
//请求时间
conn.setConnectTimeout(1000);
// 请求方式为 POST
conn.setRequestMethod("POST");
//JSON数据
conn.setRequestProperty("Content-Type","application/json");
// 输入 输出
conn.setDoOutput(true);
conn.setDoInput(true);
//连接
conn.connect();
// 传递参数流的方式
out=conn.getOutputStream();
out.write(param.getBytes());
out.flush();
// 读取数据
br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
String line=null;
while (null != (line=br.readLine())){
rest.append(line);
}
jsonObject=new JSONObject(rest.toString());
} catch (Exception e) {
e.printStackTrace();
}finally {
// 关闭所有通道
try {
if (br!=null)
br.close();
if (out!=null)
out.close();
if (conn!=null)
conn.disconnect();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return jsonObject;
}
}
使用方法:
Map<String,Object> map=new HashMap();//要传的值
map.put("key",data);
map.put("key2",123456);
JSONObject jsonObject=new JSONObject(map);//传值方式1
JSONObject jsonObject=new JSONObject();
try{
jsonObject.put("uid",MainActivity.useruid);
}catch (JSONException e) {
e.printStackTrace();
}//传值方式2
PostUtil.postrun("请求URL", jsonObject.toString(),new Handler(){//不需要传值的话第二个参数直接空字符串
@Override
public void handleMessage(Message msg) {
JSONObject jsonObject=(JSONObject)msg.obj;
try {
System.out.println(jsonObject.get("data"));//jsonObject.get("data")就是请求接口后返回的值
} catch (JSONException e) {
e.printStackTrace();
}
}
});