【发布时间】:2020-04-27 00:53:08
【问题描述】:
我在执行时打印了 json 我复制了它 我在邮递员中尝试了相同的 json 和 url 并且它正在工作,所以我认为问题不在于 url 或 json 。 main 中的 rs 变量始终为空
public class PostLocation {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
public 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 = null;
try {
response = client.newCall(request).execute(); return response.body().string();
} finally {
if (response != null) { response.close(); }
}
}
String bowlingJson(Double lg,Double lt) {
return "{\"id\": null,\"datetime\": \"2019-01-10T19:00:00.000+0000\",\"user\": {\"id\": 1 },\"latitude\": "+lt+",\"longitude\": "+lg+"}";
}
}
主要:
String rs = null;
String json = null;
//post
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
PostLocation pl = new PostLocation();
json = pl.bowlingJson(location.getLongitude(), location.getLatitude());
System.out.println(json);
rs = pl.post("http://localhost:8080/api/v1/locations", json);
}catch (IOException EX){
}finally {
t.setText("\n " + location.getLongitude() + " " + location.getLatitude() );
}
【问题讨论】:
标签: java android json post okhttp