Android okHttp网络请求Post to a Server
1. app gradle
dependencies {
implementation("com.squareup.okhttp3:okhttp:4.4.0")
2. AndroidManifest配置
<uses-permission android:name="android.permission.INTERNET" />
3. Activity代码
package com.example.myokhttppost;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
String TAG = "Main";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postRequest();
}
PostJson postJson = new PostJson();
public void postRequest() {
new Thread(new Runnable() {
@Override
public void run() {
JSONObject json = new JSONObject();
try {
json.put("node",1);
json.put("value",1);
} catch (JSONException e) {
e.printStackTrace();
}
try {
String response = postJson.post("http://www.roundsapp.com/post", String.valueOf(json));
Log.d(TAG, String.valueOf(json));
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public class PostJson {
// Post to a Server
public final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}
}
4. 关键代码
//Post to a Server
public static final MediaType JSON
= MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
//JSONObject
JSONObject json = new JSONObject();
try {
json.put("node",1);
json.put("value",1);
} catch (JSONException e) {
e.printStackTrace();
}
5.http 网络请求的问题
Android 9.0/P http 网络请求的问题
在res目录下新建xml文件夹,文件夹中新建文件network_security_config.xml,文件内容如下
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
然后在APP的AndroidManifest.xml文件下的application标签增加以下属性
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...
/>
参考链接:
Android 9.0/P http 网络请求的问题
https://www.cnblogs.com/renhui/p/9921790.html
OkHttp Post to a Server
https://square.github.io/okhttp/
同步请求
https://blog.csdn.net/fightingxia/article/details/70947701