Parse JSON z obiektu HttpURLConnection

Wykonuję podstawowy http auth z obiektem HttpURLConnection w Javie.

        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;
        }

Oczekuję obiektu JSON, lub danych łańcuchowych w formacie poprawnego obiektu JSON, lub HTML z prostym tekstem, który jest poprawny JSON. Jak uzyskać do niego dostęp z HttpURLConnection po zwróceniu odpowiedzi?

Author: CQM, 2012-05-08

5 answers

Możesz uzyskać surowe dane za pomocą poniższej metody. BTW, ten wzorzec jest dla Javy 6. Jeśli używasz Javy 7 lub nowszej, rozważ 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;
}

A następnie możesz użyć zwracanego ciągu z Google Gson aby odwzorować JSON na obiekt podanej klasy, jak to:

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

Istnieje próbka klasy 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;
    }
}

JSON zwrócony przez http://localhost/authmanager.php musi wyglądać tak:

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

Pozdrawiam

 99
Author: kbec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-01 14:05:41

Zdefiniuj następującą funkcję (nie moją, Nie wiem gdzie ją znalazłem dawno temu):

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();

}

Wtedy:

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

        // Do JSON handling here....
    }
 10
Author: Tushar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-08 14:48:04

Łańcuch JSON będzie tylko ciałem odpowiedzi otrzymanej z adresu URL, który wywołałeś. Więc dodaj ten kod

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

To pozwoli Ci zobaczyć, jak JSON jest zwracany do konsoli. Jedynym brakującym fragmentem jest użycie biblioteki JSON do odczytu tych danych i dostarczenie reprezentacji Javy.

Oto przykład użycia JSON-LIB

 2
Author: Brad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-08 14:48:24

Dodatkowo, jeśli chcesz przeanalizować swój obiekt w przypadku błędu http (400-5 * * kodów), Możesz użyć następującego kodu: (po prostu zamień 'getInputStream'na ' 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();
 2
Author: IdoT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-16 11:58:21

Ta funkcja zostanie użyta Pobierz dane z adresu url w postaci obiektu HttpResponse.

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);
}

Powyższa funkcja jest tutaj wywołana i otrzymujemy ciąg znaków json za pomocą klasy biblioteki Apache.A w poniższych wypowiedziach staramy się zrobić proste pojo z otrzymanego jsona.

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);

Jest to prosta klasa modelu Javy do obsługi json. public class JsonJavaModel{ String content; String title; } Jest to Niestandardowy deserializer:

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;
}

Include Biblioteka Gson i org.Apacz.http.util.EntityUtils;

 1
Author: Uzair,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-13 11:48:33