【问题标题】:Http request with Json response in JavaJava中带有Json响应的Http请求
【发布时间】:2014-02-11 09:35:11
【问题描述】:

我想向网站执行 HTTP 请求并接收 JSON 响应。

但是,我无法连接到主机页面。 我尝试了几个教程和技巧,但都不起作用。

try{
    String thePath = "//Url";
    thePath = URLEncoder.encode(thePath, "UTF-8"); 

    HttpGet httpget = new HttpGet(thePath);

    DefaultHttpClient httpClient = new DefaultHttpClient();

    System.out.println("Executing HTTP Get...\n");
    HttpResponse response = httpClient.execute(httpget);

    if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
        throw new RuntimeException("Failed: HTTP error code: "
            + response.getStatusLine().getStatusCode());
    }

    BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())));

    String output = ""; Boolean keepGoing = true;
    while(keepGoing){
        String currentLine = br.readLine();

        if(currentLine == null)
            keepGoing = false;
        else
            output += currentLine;
    }

    System.out.println("Raw string result: \n" + output);

} catch (MalformedURLException e){
    System.out.println("Caught MalformedURLException: " + e.toString());

} catch (IOException e){
    System.out.println("Caught IOException: " + e.toString());

} catch (Exception e){
    System.out.println("Caught Exception: " + e.toString());
}

捕获异常:java.lang.IllegalargumentException:主机名不能为空

【问题讨论】:

  • 你尝试了什么?你得到什么错误?等等等等。
  • 你到底尝试了什么?什么是问题/异常/意外行为?
  • 我尝试了 Serveral HttpGet 教程:/ 每次我尝试连接时,他都会立即崩溃并出现主机名无效的异常。我从来没有超过那一点。我尝试了我在浏览器中使用的链接,它运行良好
  • @user2814223,发布代码。否则我们怎么知道这个问题

标签: java json http connection


【解决方案1】:

移除最外层的 try/catch 块,让异常打印堆栈跟踪。然后查看堆栈顶部的方法,找到代码中导致错误方法调用的行号。学习有关该方法的文档并提供正确的论据。很可能,您提供了错误的 URL。

【讨论】: