Http使用——POST

其实和GET差不多,同样首先建一个类,

public class Http {

进行是否有网络判断

public static boolean isNetWork(Context context){
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        return info.isAvailable();
    }

请求数据POST请求

//post请求
    public static String httpPost(String str1, String str2) {
        try {
            //设置url
            URL url = new URL(str1);
            //获取HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置为post请求
            connection.setRequestMethod("POST");
            //使用写入和读取(post请求必须要写这个俩)
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //
            PrintWriter writer = new PrintWriter(connection.getOutputStream());
            writer.write(str2);
            writer.flush();
            ;//刷新
            //判断是否成功
            int code = connection.getResponseCode();
            if (code == 200) {
                //读取数据
                InputStream stream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "utf-8"));
                //拼接字符串
                StringBuilder builder = new StringBuilder();
                String s = "";
                //读取数据
                while ((s = reader.readLine()) != null) {
                    //拼接字符串
                    builder.append(s);
                }

                return builder.toString();
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

这样就可以和Handler和子线程去解析接口
记得不要忘了注册

 <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

猜你喜欢

转载自blog.csdn.net/qq_42970131/article/details/85340091
今日推荐