1. 程式人生 > >android 中okhttp post請求傳遞json資料

android 中okhttp post請求傳遞json資料

public final static int CONNECT_TIMEOUT = 60;
public final static int READ_TIMEOUT = 100;
public final static int WRITE_TIMEOUT = 60;
public static final OkHttpClient client = new OkHttpClient.Builder()
        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//設定讀取超時時間
        .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//設定寫的超時時間
        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//設定連線超時時間
        .build();

get方法
引數:
url get請求地址

    public String get(String url) throws IOException {
    Request request = new Request.Builder().url(url).get().build();
    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

post方法
引數:
url post請求地址
json json字串

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

public static String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

呼叫:

new Thread() {
    @Override
    public void run() {
        //傳的json
        JSONObject jsonObject = new JSONObject();
        try {
            String callStr = OKHttpTool.post(HttpUrl.API_ACTIVE, jsonObject.toString());
            JSONObject call_json = new JSONObject(callStr);
            final String msg = call_json.getString("msg");
            if (call_json.getInt("status") == 1){
                //在子執行緒中呼叫ui執行緒
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ActivationCardActivity.this, msg, Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}.start();