Android。Http网络请求封装。HttpClient

 前后台交互使用json数据的时候,利用handler对返回的数据进行解析,和对view的刷新

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Callhttp {
    public Callhttp(final int what, final Context context, final Class<?> obj, final Handler handler, final String urlpath, final String... json) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(urlpath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");

                    OutputStream outputStream = connection.getOutputStream();

                    JSONObject ClickKey = new JSONObject();
                    for (int i = 0, N = json.length; i < N; i += 2) {
                        if (i + 1 > N) {
                            ClickKey.put(json[i], null);
                        } else {
                            ClickKey.put(json[i], json[i + 1]);
                        }
                    }

                    String jsonbody= String.valueOf(ClickKey.toString());

                    outputStream.write(jsonbody.getBytes());

                    //int responseCode = connection.getResponseCode();
                    //请求成功 获得返回的流
                    Log.e("发送数据:",ClickKey.toJSONString());
                    Log.e("url:",urlpath);

                    InputStream inputStream = connection.getInputStream();
                    String value;
                    value = readStreamToString(inputStream);

                    Log.e("value:",value);

                    Message message = Message.obtain();
                    message.what=what;
                    message.obj =JSON.parseObject(value, obj);
                    handler.sendMessage(message);

                    inputStream.close();
                    outputStream.close();
                } catch (MalformedURLException e) {
                    Looper.prepare();
                    Toast.makeText(context.getApplicationContext(),"请检查网络连接",Toast.LENGTH_SHORT).show();
                    Log.e("请检查网络连接","请检查网络连接");
                    e.printStackTrace();
                    Looper.loop();
                } catch (IOException e) {
                    Looper.prepare();
                    Toast.makeText(context.getApplicationContext(),"服务器不可用",Toast.LENGTH_SHORT).show();
                    Log.e("服务器不可用","服务器不可用");
                    e.printStackTrace();
                    Looper.loop();
                }
            }
        }).start();
    }

   //无参数get请求
    public Callhttp(final int what, final int arg1, final Context context, final Class<?> obj, final Handler handler, final String urlpath) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(urlpath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");

                    Log.e("url:",urlpath);

                    //请求成功 获得返回的流
                    InputStream inputStream = connection.getInputStream();
                    String value;
                    value = readStreamToString(inputStream);

                    //Log.e("发送数据:",json.toJSONString());


                    Log.e("value:",value);

                    Message message = Message.obtain();
                    message.arg1=arg1;
                    message.what=what;
                    message.obj =JSON.parseObject(value, obj);
                    handler.sendMessage(message);

                    inputStream.close();
                } catch (MalformedURLException e) {
                    Looper.prepare();
                    Toast.makeText(context.getApplicationContext(),"请检查网络连接",Toast.LENGTH_SHORT).show();
                    Log.e("请检查网络连接","请检查网络连接");
                    e.printStackTrace();
                    Looper.loop();
                } catch (IOException e) {
                    Looper.prepare();
                    Toast.makeText(context.getApplicationContext(),"服务器不可用",Toast.LENGTH_SHORT).show();
                    Log.e("服务器不可用","服务器不可用");
                    e.printStackTrace();
                    Looper.loop();
                }
            }
        }).start();
    }

    public Callhttp(final int what, final Context context, final Class<?> obj, final Handler handler, final String urlpath) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(urlpath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");

                    //请求成功 获得返回的流
                    InputStream inputStream = connection.getInputStream();
                    String value;
                    value = readStreamToString(inputStream);

                    //Log.e("发送数据:",json.toJSONString());
                    Log.e("url:",urlpath);
                    Log.e("value:",value);

                    Message message = Message.obtain();
                    message.what=what;
                    message.obj =JSON.parseObject(value, obj);
                    handler.sendMessage(message);

                    inputStream.close();
                } catch (MalformedURLException e) {
                    Looper.prepare();
                    Toast.makeText(context.getApplicationContext(),"请检查网络连接",Toast.LENGTH_SHORT).show();
                    Log.e("请检查网络连接","请检查网络连接");
                    e.printStackTrace();
                    Looper.loop();
                } catch (IOException e) {
                    Looper.prepare();
                    Toast.makeText(context.getApplicationContext(),"服务器不可用",Toast.LENGTH_SHORT).show();
                    Log.e("服务器不可用","服务器不可用");
                    e.printStackTrace();
                    Looper.loop();
                }
            }
        }).start();
    }


    public String readStreamToString(InputStream inputStream) throws IOException {
        //创建字节数组输出流 ,用来输出读取到的内容
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //创建读取缓存,大小为1024
        byte[] buffer = new byte[1024];
        //每次读取长度
        int len = 0;
        //开始读取输入流中的文件
        while( (len = inputStream.read(buffer) ) != -1){ //当等于-1说明没有数据可以读取了
            byteArrayOutputStream.write(buffer,0,len); // 把读取的内容写入到输出流中
        }
        //把读取到的字节数组转换为字符串
        String result = byteArrayOutputStream.toString();

        //关闭输入流和输出流
        inputStream.close();
        byteArrayOutputStream.close();
        //返回字符串结果
        return result;
    }
}

使用的话

 new Callhttp(1,activity, BaseBean.class,handler, url);
            
  protected void getMessage(Message msg) {
        if (msg.what==1){
            BaseBean baseBean= (BaseBean) msg.obj;
            String result= (String) baseBean.getResult();
            if (result.equals("0")){
                ifnum=false;
                nonum.setVisibility(View.VISIBLE);
            }else {
                ifnum=true;
                nonum.setVisibility(View.GONE);
            }
        }else if (msg.what==2){
            BaseBean baseBean= (BaseBean) msg.obj;
            if (baseBean.isSuccess()){
                Toast.makeText(activity, "备案成功", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(activity, MainActivity.class));
            }else {
                Toast.makeText(activity,baseBean.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

第一个参数给message.what判断区分请求,之后是上下文,解析成的数据,handler,url地址。

根据需要还可以用post方法

            new Callhttp(2,activity, BaseBean.class,handler, url,
                            "platenumber",platenumber.getText().toString().trim(),
                            "vin",vin.getText().toString().trim()
                            );

只需要把key值和value写上就好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值