我正在用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对象格式的字符串数据,或者具有有效JSON的简单纯文本的HTML。在它返回响应后,我如何从HttpURLConnection
访问它?
发布于 2012-05-08 23:24:37
您可以使用以下方法获取原始数据。顺便说一句,此模式适用于Java6。如果您使用的是Java7或更高版本,请考虑使用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映射到指定类的object,如下所示:
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"}
问候
发布于 2012-05-08 22:48:05
定义以下函数(不是我的,不确定我很久以前在哪里找到的):
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....
}
发布于 2014-06-16 19:58:22
此外,如果您希望在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();
https://stackoverflow.com/questions/10500775
复制相似问题