androidでok httpはjsonデータを転送します。

2413 ワード

参照アドレスhttp://blog.csdn.net/lmj623565791/article/details/47911083 client基本配置
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文字列
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();