[英]How to make http call from standalone java application
我正在使用Java swing创建一个小型字典类的应用程序。 我为此使用牛津字典API。 有没有办法在不使用servelet和所有高级java概念的情况下用java发出简单的ajax请求。 就像在android中一样,我们使用http url连接来完成这项工作。我在Google上进行了大量的搜索,但是我找不到解决方案,因为每个页面都使用servelet显示结果。 但是我只了解核心Java,如果可以在不使用Servlts的情况下进行Ajax调用,请帮助我...在此先感谢...
使用HttpURLConnection
类进行http调用。
如果您需要更多的帮助,了解,然后去的java的官方文档站点这里例
public class JavaHttpUrlConnectionReader {
public static void main(String[] args) throws IOException{
String results = doHttpUrlConnectionAction("https://your.url.com/", "GET");
System.out.println(results);
}
public static String doHttpUrlConnectionAction(String desiredUrl, String requestType) throws IOException {
BufferedReader reader = null;
StringBuilder stringBuilder;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(desiredUrl).openConnection();
connection.setRequestMethod(requestType);// Can be "GET","POST","DELETE",etc
connection.setReadTimeout(3 * 1000);
connection.connect();// Make call
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));// Reading Responce
stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
return stringBuilder.toString();
} catch (IOException e) {
throw new IOException("Problam in connection : ", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ioe) {
throw new IOException("Problam in closing reader : ", ioe);
}
}
}
}
}
它将进行呼叫并以返回字符串形式给出响应。 如果您想进行POST呼叫,则需要为此做一些额外的工作:
try{
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(postParam.getBytes());
} catch(IOException e){
}
注意:这里的postParam
是String
类型,其值类似于"someId=156422&someAnotherId=32651"
并将此porson放在connection.connect()
语句之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.