用OKHTTP框架做服务器通信

OkHttp一些基本步骤我就不多说啦,我的其他关于OkHttpde博客中写的很详细。

public class MainActivity extends AppCompatActivity {
    OkHttpClient okHttpClient = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void Post(View view){
        Thread t1=new Thread(new Runnable() {
            @Override
            public void run() {
                MediaType JSON = MediaType.parse("text/x-markdown; charset=utf-8");
                List<Map<String,String>> list=new ArrayList<>();//将JSON数据以Map形式存储到list中,以list数组形式存储数据。
                Map<String,String> map1=new HashMap<>();
                Map<String,String> map2=new HashMap<>();
                map1.put("Name","T1");
                map1.put("Value","90");
                map2.put("Name","T2");
                map2.put("Value","90");
                list.add(map1);
                list.add(map2);
                JSONArray jsonArray=new JSONArray(list);
                String string=jsonArray.toString();
                RequestBody requestBody= RequestBody.create(JSON,string);//将JSON数据打包成Body通过post上传;
                Request request=new Request.Builder()
                        .url("http://www.lewei50.com/api/V1/gateway/UpdateSensors/01")
                        .addHeader("userkey","d4443f13d39a42ccbd20ad9ade868f3d")
                        .post(requestBody)
                        .build();
                executeRequest(request);
            }
        });
        t1.start();
    }
    private void executeRequest(Request request){
        Call call=new OkHttpClient().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.i("tAG","错误");
            }

            @Override
            public void onResponse(Response response) throws IOException {
               final  String result=response.body().string();//接收服务器返回来的信息
                try {
                    /*JSONObject jsonObject=new JSONObject(result);*///将返回的信息转换成JSON形式
                    JSONObject jsonObject =new  JSONObject("Successful");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}

 

Post数据

[
    {
        "Name":"T1",
        "Value":"90"
    },
    {
        "Name":"T2",
        "Value":"90"
    }
]

 使用到了JSON,{}代表一个map集合,[]是一个list集合。post数据中,有两个map集合,两个map集合放在了list集合中。

返回结果实例

{
    "Successful": true, 
    "Message": null
}

我们返回是上面这种格式,所以将返回的数据转成JSONObject形式,而不是JSONArray的形式.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个使用 OkHttp 实现 Socket 通信的示例代码: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okio.BufferedSink; public class SocketClient { private static final String HOST = "example.com"; // 服务器地址 private static final int PORT = 12345; // 服务器端口号 private static final MediaType MEDIA_TYPE_PLAIN_TEXT = MediaType.parse("text/plain"); private OkHttpClient client; private Socket socket; private BufferedSink sink; public void connect() throws IOException { client = new OkHttpClient(); socket = new Socket(); socket.connect(new InetSocketAddress(HOST, PORT), 5000); // 连接超时时间为 5 秒 sink = Okio.buffer(Okio.sink(socket)); } public void disconnect() throws IOException { socket.close(); } public void send(String message) throws IOException { sink.writeUtf8(message); sink.flush(); } public String receive() throws IOException { Request request = new Request.Builder() .url("http://" + HOST + ":" + PORT) .post(RequestBody.create(MEDIA_TYPE_PLAIN_TEXT, "")) .build(); Response response = client.newCall(request).execute(); ResponseBody body = response.body(); if (body == null) { return null; } return body.string(); } } ``` 在上面的代码中,我们使用 OkHttp 的 `OkHttpClient` 类来发送 HTTP POST 请求,以接收服务器发送的消息。`send` 方法使用 Okio 的 `BufferedSink` 类将消息写入 Socket 连接。使用时需要注意在合适的时机调用 `connect` 方法连接服务器,并在不需要连接时调用 `disconnect` 方法断开连接。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值