从HttpURLConnection对象解析JSON

时间:2012-05-08 14:37:56

标签: java html json parsing httpurlconnection

我正在使用Java中的HttpURLConnection对象进行基本的http auth。

        URL urlUse = new URL(url);
        HttpURLConnection conn = null;
        conn = (HttpURLConnection) urlUse.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-length", "0");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
        conn.connect();

        if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
        {
            success = true;
        }

我期待一个JSON对象,或者是有效JSON对象格式的字符串数据,或者是带有简单明文的HTML,它是有效的JSON。如何在HttpURLConnection返回响应后访问该文件?

5 个答案:

答案 0 :(得分:103)

您可以使用以下方法获取原始数据。顺便说一句,这种模式适用于Java 6.如果您使用的是Java 7或更高版本,请考虑try-with-resources pattern

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

然后你可以使用带有Google Gson的返回字符串将JSON映射到指定类的对象,如下所示:

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

有一个AuthMsg类的示例:

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

http://localhost/authmanager.php返回的JSON必须如下所示:

{"code":1,"message":"Logged in"}

此致

答案 1 :(得分:10)

定义以下功能(不是我的,不知道我很久以前在哪里找到它):

private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
return sb.toString();

}

然后:

String jsonReply;
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
    {
        success = true;
        InputStream response = conn.getInputStream();
        jsonReply = convertStreamToString(response);

        // Do JSON handling here....
    }

答案 2 :(得分:2)

JSON字符串将只是您从所调用的URL返回的响应的主体。所以添加此代码

...
BufferedReader in = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) 
    System.out.println(inputLine);
in.close();

这将允许您查看返回到控制台的JSON。您拥有的唯一缺失的部分是使用JSON库来读取该数据并为您提供Java表示。

Here's an example using JSON-LIB

答案 3 :(得分:2)

另外,如果你想在http错误(400-5 **代码)的情况下解析你的对象, 您可以使用以下代码:(只需将'getInputStream'替换为'getErrorStream':

    BufferedReader rd = new BufferedReader(
            new InputStreamReader(conn.getErrorStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();
    return sb.toString();

答案 4 :(得分:1)

此函数将用于以HttpResponse对象的形式从url获取数据。

public HttpResponse getRespose(String url, String your_auth_code){
HttpClient client = new DefaultHttpClient();
HttpPost postForGetMethod = new HttpPost(url);
postForGetMethod.addHeader("Content-type", "Application/JSON");
postForGetMethod.addHeader("Authorization", your_auth_code);
return client.execute(postForGetMethod);
}

在这里调用上面的函数,我们使用Apache库Class.And接收json的String形式。在下面的语句中,我们尝试从我们收到的json中创建简单的pojo。

String jsonString     =     
EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/    blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new    CustomJsonDeserialiser());
final Gson gson = gsonBuilder.create();
JsonElement json = new JsonParser().parse(jsonString);
JsonJavaModel pojoModel = gson.fromJson(
                    jsonElementForJavaObject, JsonJavaModel.class);

这是一个用于输入json的简单java模型类。     公共类JsonJavaModel {     字符串内容;     字符串标题;     } 这是一个自定义反序列化器:

public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel>         {

@Override
public JsonJavaModel deserialize(JsonElement json, Type type,
                                 JsonDeserializationContext arg2) throws    JsonParseException {
    final JsonJavaModel jsonJavaModel= new JsonJavaModel();
    JsonObject object = json.getAsJsonObject();

    try {
     jsonJavaModel.content = object.get("Content").getAsString()
     jsonJavaModel.title = object.get("Title").getAsString()

    } catch (Exception e) {

        e.printStackTrace();
    }
    return jsonJavaModel;
}

包括Gson库和org.apache.http.util.EntityUtils;