我想对网站执行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());
}
Caught Exception:java.lang.IllegalargumentException:主机名可能不为null
答案 0 :(得分:0)
删除最外层的try / catch块,让异常打印堆栈跟踪。然后查看堆栈顶部的方法,找到代码中的行号,这会导致错误的方法调用。学习该方法的文档并提供正确的参数。最有可能的是,您提供了错误的网址。