我正在使用 Java 中的 HttpURLConnection
对象进行基本的 http 身份验证。
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 对象格式的字符串数据,或带有有效 JSON 的简单纯文本的 HTML。 HttpURLConnection
返回响应后如何访问它?
最佳答案
您可以使用以下方法获取原始数据。顺便说一句,此模式适用于 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"}
问候
关于java - 从 HttpURLConnection 对象解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10500775/