我在执行时打印了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+"}";
}
}
主要:
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.net.ConnectException:我用10.0.2.2更改了localhost(127.0.0.1),因为Android模拟器在虚拟机中运行
然后我有一个问题java.net.SocketTimeoutException:我添加了超时:
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();
现在可以了
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句