今天给OkHttp发送字段说下,这样OkHttp的基本用法想来大家能够简单的写出来了。希望能帮助到大家。
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() {
postParams();
}
}.start();
}
private void postParams() {
//创建一个OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//构建一个请求体 add参数1 key 参数2 value 发送字段
RequestBody requestBody = new FormEncodingBuilder()
.add("platform", "android")
.add("version", "23")
.add("SDK", "24")
.build();
//构建一个请求对象
Request request = new Request.Builder()
.url("http://192.168.0.102:8080/TestProject/ParamServlet")
.post(requestBody)
.build();
//发送请求获取响应
Response response=null;
try {
response = okHttpClient.newCall(request).execute();
//判断请求是否成功
if(response.isSuccessful()){\
//打印服务端返回结果
Log.i(TAG,response.body().string());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
第一篇地址 http://www.jianshu.com/p/cd8d03d4286e
第二篇地址 http://www.jianshu.com/p/7e25bb49c36c
网友评论