[英]Http request with Json response in Java
我想对网站执行HTTP请求并接收JSON响应。
但是,我无法管理“连接到主机页面”。 我尝试了一些教程和技巧,但无法正常工作。
try{
String thePath = "//Url";
thePath = URLEncoder.encode(thePath, "UTF-8");
HttpGet httpget = new HttpGet(thePath);
DefaultHttpClient httpClient = new DefaultHttpClient();
System.out.println("Executing HTTP Get...\n");
HttpResponse response = httpClient.execute(httpget);
if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed: HTTP error code: "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output = ""; Boolean keepGoing = true;
while(keepGoing){
String currentLine = br.readLine();
if(currentLine == null)
keepGoing = false;
else
output += currentLine;
}
System.out.println("Raw string result: \n" + output);
} catch (MalformedURLException e){
System.out.println("Caught MalformedURLException: " + e.toString());
} catch (IOException e){
System.out.println("Caught IOException: " + e.toString());
} catch (Exception e){
System.out.println("Caught Exception: " + e.toString());
}
捕获的异常:java.lang.IllegalargumentException:主机名不能为null
删除最外面的try / catch块,让异常打印堆栈跟踪。 然后查看堆栈顶部的方法,在代码中找到导致错误方法调用的行号。 学习有关该方法的文档并提供正确的参数。 您很可能提供了错误的URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.