[英]How to make http call from standalone java application
I'm making a small dictionary kind of app using java swings. 我正在使用Java swing创建一个小型字典类的应用程序。 I'm using oxford dictionary api for that.
我为此使用牛津字典API。 Is there any way to make a simple ajax request in java without using servelets and all advanced java concepts.
有没有办法在不使用servelet和所有高级java概念的情况下用java发出简单的ajax请求。 As in android we use http url connection to do this job.I googled a lot for finding this but I could't find a solution as every page is showing results using servelets.
就像在android中一样,我们使用http url连接来完成这项工作。我在Google上进行了大量的搜索,但是我找不到解决方案,因为每个页面都使用servelet显示结果。 But I know core java alone.If it is possible to make ajax call without servelts please help me...Thanks in advance...
但是我只了解核心Java,如果可以在不使用Servlts的情况下进行Ajax调用,请帮助我...在此先感谢...
Use HttpURLConnection
class to make http call. 使用
HttpURLConnection
类进行http调用。
If you need more help for that then go for offical documentation site of java Here Example 如果您需要更多的帮助,了解,然后去的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);
}
}
}
}
}
It will make a call and give response as return string. 它将进行呼叫并以返回字符串形式给出响应。 If you want to make POST call the need to do some extra for that :
如果您想进行POST呼叫,则需要为此做一些额外的工作:
try{
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(postParam.getBytes());
} catch(IOException e){
}
Note : Here postParam
is String
type with value somthing like "someId=156422&someAnotherId=32651"
注意:这里的
postParam
是String
类型,其值类似于"someId=156422&someAnotherId=32651"
And put this porson befor connection.connect()
statement. 并将此porson放在
connection.connect()
语句之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.