Android -- 簡單的POST請求

一 、post請求方法:

String post(String url, String json) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormEncodingBuilder()
                .add("v_image", "android2017_01")
                .add("imageTitle", "2017")
                .add("imageDescription", "zeng")
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

二 、調用

new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String str = post(rURL, "");
                            Log.i("ExceptionIO",str);
                        } catch (IOException e) {
                            Log.i("ExceptionIO",e.toString());
                            e.printStackTrace();
                        }
                    }
                }).start();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章