public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
public static final MediaType JSON=MediaType.parse("application/json; charset=utf-8");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//开启一个线程,做联网操作
new Thread() {
@Override
public void run() {
postJson();
}
}.start();
}
private void postJson() {
//申明给服务端传递一个json串
//创建一个OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//创建一个RequestBody(参数1:数据类型 参数2传递的json串)
//json为String类型的json数据
RequestBody requestBody = RequestBody.create(JSON, json);
//创建一个请求对象
Request request = new Request.Builder()
.url("http://192.168.0.102:8080/TestProject/JsonServlet")
.post(requestBody)
.build();
//发送请求获取响应
try {
Response response=okHttpClient.newCall(request).execute();
//判断请求是否成功
if(response.isSuccessful()){\
//打印服务端返回结果
Log.i(TAG,response.body().string());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}