我在执行时打印了json,然后复制了它,我在邮递员中尝试了相同的json和url,并且它可以正常工作,所以我不认为问题出在url或json。 main中的rs变量始终为null
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+"}";
}
}
main:
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() );
}
这是您格式化的Json:
{
"id":null,
"datetime":"2019-01-10T19:00:00.000+0000",
"user":{
"id":1
},
"latitude":"+lt+",
"longitude":"+lg+"
}
在我看来,lt
和lg
总是在其周围带有+。
为什么不使用String.format
:
String.format("{\"id\": null,\"datetime\": \"2019-01-10T19:00:00.000+0000\",\"user\": {\"id\": 1 },\"latitude\": %f,\"longitude\": %f}", lt, lg);
问题是java.net.ConnectException:我用10.0.2.2更改了localhost(127.0.0.1),因为Android模拟器在虚拟机中运行
然后我遇到一个问题java.net.SocketTimeoutException:timeout我加了:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
.writeTimeout(5, TimeUnit.MINUTES) // write timeout
.readTimeout(5, TimeUnit.MINUTES); // read timeout
client = builder.build();
现在正在工作