【问题标题】:Okhttp post return nullOkhttp 帖子返回 null
【发布时间】: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


    【解决方案1】:

    问题是 java.net.ConnectException : 我将 localhost(127.0.0.1) 更改为 10.0.2.2,因为 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();
    

    现在可以了

    【讨论】:

      【解决方案2】:

      这是您的格式化 Json:

      { 
       "id":null,
       "datetime":"2019-01-10T19:00:00.000+0000",
       "user":{ 
        "id":1
       },
       "latitude":"+lt+",
       "longitude":"+lg+"
      }
      

      在我看来,ltlg 周围总是有 +。

      为什么不使用String.format,例如:

      String.format("{\"id\": null,\"datetime\": \"2019-01-10T19:00:00.000+0000\",\"user\": {\"id\": 1 },\"latitude\": %f,\"longitude\": %f}", lt, lg);
      

      【讨论】:

      • 我尝试过,但同样的问题,就像我说的问题不在 json 字符串或 url 中,因为我在执行应用程序时打印返回的字符串并且我制作了相同的 json 和相同的 url在邮递员中,它正在工作
      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 2015-06-20
      • 2014-12-09
      • 2015-07-09
      • 1970-01-01
      • 2011-11-16
      • 2012-05-20
      • 1970-01-01
      相关资源
      最近更新 更多