【问题标题】:URL construction using okHttpClient使用 okHttpClient 构建 URL
【发布时间】:2018-05-19 10:18:44
【问题描述】:

我在使用 okHttpClient 构建 URL 时遇到问题。我正进入(状态 URL 构造中的以下错误 (http://16.234.156.25:88/example)

请找到代码:

public static void main(String[] args) throws IOException, URISyntaxException {
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();

            String host = "16.234.156.25";
            int port = 88;

            String port1 = Integer.toString(port);
            String ipadd = host + ":" + port1;

            URI uri = new URI(ipadd);
            String finalURL = uri.toString();

            HashMap<String, String> map = new HashMap<>();

            map.put("", finalURL):

            for (Entry<String, String> m : map.entrySet()) {

                Request request = new Request.Builder()

                        .url("http://" + m.getValue() + "/example").get()
                        .addHeader("cache-control", "no-cache")
                        .addHeader("postman-token", "e6335509-3e1d-54c8-a975-dc9430e6d115").build();

错误:

线程“主”java.net.URISyntaxException 中的异常:非法 索引 0 处的方案名称中的字符:16.234.156.25:88 at java.net.URI$Parser.fail(URI.java:2848)

【问题讨论】:

  • 那是因为你的ipadd会变成16.234.156.25:88。将 ipadd 更改为 "String ipadd = "http://" + host + ":" + port1;"
  • 我已经在请求 url (.url("http://" + m.getValue() + "/example").get()) 中添加了“http://”,我想要只添加主机和端口
  • 即 16.234.156.25:88
  • URI uri = 新的 URI(ipadd);这不接受主机:端口。
  • 这里用冒号代替分号:map.put("", finalURL):

标签: java okhttp3


【解决方案1】:

错误信息非常好。 “方案”是 URL 的第一部分,在“://”之前。问题是你没有提供。我猜你需要一个“http”或“https”。查看 URI 类的 Javadoc;您需要的不仅仅是 IP 地址。

祝你好运。

【讨论】:

  • 我已经在请求 url (http://" + m.getValue() + "/example").get()) 中给出了方案名称。我希望 m.getValue() 为 16.234 .156.25:88
  • 查看整个堆栈跟踪。您的代码的哪一行是异常的来源? “http://”在您的代码中出现在哪一行?如果是在另一条线之后,那就太晚了。正如我所说,问题在于 URI 实例的构造。
猜你喜欢
  • 1970-01-01
  • 2016-11-16
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 2015-02-14
相关资源
最近更新 更多