java怎么接收接口请求的json数据

2024-12-21 10:43:52
推荐回答(2个)
回答1:

public void test(Long clusterId,boolean monitorSendAllFlag) {
boolean result=false;
try {
String url ="http://www.xxx.com/xxx/xxx.action";
String json= HttpConfigUtil.getHttpResponse(url);
System.out.println(json);

} catch (Exception e) {
e.printStackTrace();
}

}

public static String getHttpResponse(String allConfigUrl) {
BufferedReader in = null;
StringBuffer result = null;
try {

URI uri = new URI(allConfigUrl);
URL url = uri.toURL();
URLConnection connection = url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Charset", "utf-8");

connection.connect();

result = new StringBuffer();
//读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}

return result.toString();

} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}

return null;

}

回答2:

public class HttpJSONTest {

/**
* @param args
*/
public static void main(String[] args) {
String url = "http://www.baidu.com";
String json = loadJSON(url);
System.out.println(json);
}

public static String loadJSON (String url) {
StringBuilder json = new StringBuilder();
try {
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine = null;
while ( (inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return json.toString();
}
}