【问题标题】:URLConnection Reading in as null in javaURLConnection 在java中读为null
【发布时间】:2014-09-27 15:57:49
【问题描述】:

我正在构建一个基本程序来查询 Target 的 API,其中包含商店 ID 和产品 ID,它返回过道位置。但是,我认为我错误地使用了 URL 构造函数(我过去遇到过麻烦,但仍然不完全理解它们)。下面是我拥有的代码,出于显而易见的原因编辑了 API 密钥。我创建的 URL 在放入浏览器时是有效的,并且没有抛出异常,但最后当我打印出页面的内容时它是空的。我错过了什么?非常感谢任何帮助!

package productVerf;

import java.net.*;
import java.io.*;

public class Verify {
    public static void main(String args[]) {
        // first input is store id second input is product id
        String productID = args[0];
        String storeID = args[1];
        String file = "/v2/products/storeLocations?productId=" + productID
                + "&storeId=" + storeID
                + "&storeId=694&key=REDACTED";
        URL locQuery;
        URLConnection lqConection = null;
        try {

            locQuery = new URL("http", "api.target.com", file);
            lqConection = locQuery.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedReader response;
        String responseString = "";
        try {
            response = new BufferedReader(new InputStreamReader(
                    lqConection.getInputStream()));
            while (response.readLine() != null) {
                responseString += response.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(responseString);

    }
}

【问题讨论】:

  • 收到响应码后会得到什么?

标签: java url bufferedreader nul


【解决方案1】:

也许你只阅读偶数行

你读了两遍一行? (在 while 语句中...),看起来您读取了放入 while 条件测试的第一行。如果您的回复仅包含一行,则不会读取任何内容

使用这个:

String line;
while ((line=response.readLine()) != null) {
       responseString += line;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多