Xutils Post请求带加载弹框

Android开发时我们需要使用到网络请求,大部分请求需要一个加载圈提示用户正在加载,我做了一个粗糙的请求加载供大家参考。

public class XutilsHttpPost {
    //加载弹框
    private  Dialog dialog;
    //弹框内的布局
    private  RelativeLayout view;
    //弹框显示页面
    private Context context;
    public XutilsHttpPost() {
        context = null;
    }
    //构造方法(参数可以传null,传null时与上一个构造方法相同,代表该请求不显示加载弹框)
    public XutilsHttpPost(Context context) {
        this.context=context;
    }
    //弹框操作(弹框操作只能在主线程里进行,切记!)
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //判断是否需要创建弹框
            if (dialog == null&&context!=null){
                //弹框样式很粗糙可以改变
                dialog = new Dialog(context,R.style.customDialog);
                //创建显示内容
                view = new RelativeLayout(context);
                view.setGravity(Gravity.CENTER);
                ProgressBar progressBar = new ProgressBar(MyApplication.getContext());
                view.addView(progressBar);
                dialog.setContentView(view);
            }
            //判断弹框是否需要显示以及开启或者关闭
            if (context != null) {
                if (dialog.isShowing())
                    dialog.dismiss();
                else
                    dialog.show();
            }
        }
    };


    //判断网络是否连接:返回值 -1:没有网络  1:WIFI网络2:wap网络3:net网络
    public int GetNetype()
    {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) MyApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if(networkInfo==null)
        {
            return netType;
        }
        int nType = networkInfo.getType();
        if(nType==ConnectivityManager.TYPE_MOBILE)
        {
            if(networkInfo.getExtraInfo().toLowerCase().equals("cmnet"))
            {
                netType = 3;
            }
            else
            {
                netType = 2;
            }
        }
        else if(nType==ConnectivityManager.TYPE_WIFI)
        {
            netType = 1;
        }
        return netType;
    }
    /**
     * 返回jsonobject的接口(这里只有成功后返回数据的参数,可以加一个成功或失败的参数)
     */
    public interface GetJson{
        void getjson(JSONObject obj);
    }

    /**
     * 请求方法
     * @param uri 路径
     * @param params 参数 (只是将RequestParams封装了一下方便查看参数内容)
     * public class MParams extends RequestParams {
    *private Map<String,String> map;
    *
    *public MParams() {
    *map = new HashMap<String, String>();
    *}
    *public void add(String name, String value){
    *addBodyParameter(name,value);
    *map.put(name,value);
    *}

     *@Override
     *public String toString() {
     *return map.toString();
     *}
     *}
     * @param getJson 接收接口
     */
    public void Post(final String uri, final MParams params, final GetJson getJson){
        if (GetNetype() == -1){
            ToastUtil.show("请检查网络是否开启!");
            return;
        }

        //默认传入用户Token
        params.add("token", UserInfo.Token);//"26245f1ae9114772b2449630ed3185f8");
        //传入了超时时间
        HttpUtils http = new HttpUtils(20000);
        http.send(HttpRequest.HttpMethod.POST,
                uri,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart(){
                        if (context != null)
                        handler.sendMessage(new Message());
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (isUploading) {

                        } else {

                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        if (context != null)
                            handler.sendMessage(new Message());
                        L.d("返回参数》",responseInfo.result+"《");
                        //判断返回数据是否为空
                        if (responseInfo.result.length() != 0) {
                            try {
                                JSONObject jsonObject = JSONObject.parseObject(responseInfo.result);
                                if (!jsonObject.getBoolean("success")) {
                                    ToastUtil.show(jsonObject.getString("message"));
                                }
                                //将数据传入页面
                                getJson.getjson(jsonObject);
                            } catch (JSONException e) {
                                L.d("异常",e.getMessage());
                                ToastUtil.show("返回参数格式错误");
                                L.d("请求路径-----》" + uri);
                                L.d("返回参数-----》" + responseInfo.result);
                            }
                        }else {
                            L.d("收到参数为空");
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        if (context != null)
                            handler.sendMessage(new Message());
                        ToastUtil.show("网络请求失败");
                        L.d("请求路径-----》" + uri+"?"+params.toString());
                        L.d("————————————————————错误信息————————————",msg);
                        L.d("————————————————————网络请求失败errorCode————————————",""+error.getExceptionCode());
                    }
                });
    }

}
样式比较粗糙,希望能给大家提供思路。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 Java 中发送 POST 请求有多种方法,以下是使用 java.net 包中的 URLConnection 类的示例代码: ``` import java.io.*; import java.net.*; public class Main { public static void main(String[] args) throws Exception { URL url = new URL("http://example.com/post"); URLConnection con = url.openConnection(); HttpURLConnection http = (HttpURLConnection)con; http.setRequestMethod("POST"); // 设置 HTTP 请求方法为 POST http.setDoOutput(true); // 发送 POST 请求 DataOutputStream out = new DataOutputStream(http.getOutputStream()); out.writeBytes("key1=value1&key2=value2"); out.flush(); out.close(); // 读取响应 BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); } } ``` 还有其他方法,例如使用 Apache HttpClient 库或者使用 Java 8 中的 java.net.http 包中的 HTTP Client。 注意:在发送 POST 请求时,需要设置 HTTP 请求头中的 Content-Type 字段,以指示发送的数据的类型。例如,如果发送的是表单数据,则应将 Content-Type 设置为 application/x-www-form-urlencoded。 ### 回答2: 在Java中,我们可以使用HttpClient库来发送POST请求。首先,我们需要导入相关的依赖库,如Apache HttpComponents Client。 接下来,我们可以创建一个HttpPost对象,并设置需要发送的URL地址。我们可以通过HttpPost的构造函数来设置URL,或者通过setURI方法来设置。 然后,我们可以设置需要发送的数据。我们可以使用NameValuePair来表示参数名和对应的值。我们可以创建一个List<NameValuePair>对象,并将所有的参数添加到列表中。然后,我们可以使用UrlEncodedFormEntity来表示编码后的参数,将其设置为HttpPost的entity。 最后,我们可以创建一个DefaultHttpClient对象,并执行HttpPost请求。我们可以使用execute方法来发送请求,并得到响应。响应的结果可以通过HttpResponse对象来获取。可以通过getEntity方法来获取响应的实体,然后使用BufferedReader来读取实体中的内容并打印出来。 以下是一个示例代码片段,演示了如何发送POST请求: ```java import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class PostExample { public static void main(String[] args) throws Exception { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://example.com/post"); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } } } ``` 这样,我们就可以使用Java发送POST请求了。当然,根据实际需求,还可以设置其他的请求头、设置代理、设置超时时间等。 ### 回答3: Java 发送 POST 请求可以通过使用 Java 的 HttpURLConnection 类来实现。下面是一个简单的例子: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpPostExample { public static void main(String[] args) { try { // 指定 POST 请求的 URL URL url = new URL("http://example.com/api/endpoint"); // 创建 HttpURLConnection 对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为 POST connection.setRequestMethod("POST"); // 允许输出请求内容 connection.setDoOutput(true); // 设置请求体内容 String requestBody = "key1=value1&key2=value2"; DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(requestBody); outputStream.flush(); outputStream.close(); // 获取请求响应 int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 输出响应内容 System.out.println("Response Content: " + response.toString()); // 关闭连接 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码展示了如何使用 HttpURLConnection 类发送 POST 请求。你可以通过设置请求方法为 `POST`,设置请求体内容并获取响应来实现发送 POST 请求。在这个例子中,我们假设请求体以键值对的形式传递。你也可以根据实际需求修改请求体的格式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值