从HttpURLConnection对象parsingJSON

我正在用Java中的HttpURLConnection对象进行基本的httpauthentication。

  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对象格式的string数据,或简单的纯文本是有效的JSON的HTML。 在返回响应后,如何从HttpURLConnection访问它?

您可以使用下面的方法获取原始数据。 顺便说一句,这种模式是Java 6的。如果你使用Java 7或更新的,请考虑尝试与资源模式 。

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

然后你可以使用返回的string与谷歌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"} 

问候

定义下面的函数(不是我的,不知道我以前在哪里find它):

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

JSONstring将只是您从调用的URL返回的响应的主体。 所以添加这个代码

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

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

这是一个使用JSON-LIB的例子

另外,如果你希望在发生http错误(400-5 **代码)的情况下parsing你的对象,你可以使用下面的代码:(只要用'getErrorStream'代替'getInputStream':

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

这个函数将用来从HttpResponse对象的forms获取来自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来接收JSON的一个Stringforms。在下面的语句中,我们试图从我们收到的json中创build一个简单的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); 

这是一个简单的java模型类,用于inputjson。 公共类JsonJavaModel {string内容; string标题; }这是一个自定义的反序列化器:

 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;