我有一个网址,当我们在浏览器中运行该网址时发送短信。我在java中试过这个。以下是我的代码:
URL myURL = new URL("http://example.com/");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
我想在不打开浏览器的情况下运行网址。但问题是我没有收到任何短信(即代码不起作用)。我特意尝试在浏览器中运行url并且我收到了短信,所以url没问题。以上代码基于互联网的一些参考。任何帮助都是适当的。纠正我是我完全错误的解决方案。
答案 0 :(得分:1)
您的代码存在的问题是,您永远不会调用getInputStream()
,getContent()
或getHeaderField()
,这将实际启动场景后的请求。
试试这个:
URL myURL = new URL("http://example.com/");
URLConnection myURLConnection = myURL.openConnection();
try (InputStream is = myURLConnection.getInputStream()) {}
或者简单地说:
URL myURL = new URL("http://example.com/");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.getContentLength(); // -> calls getHeaderField("content-length")
NB:上面列出的3种方法会自动调用connect()
,因此无需再明确调用它。
答案 1 :(得分:0)
public String SendSMS() {
StringBuilder sURL = new StringBuilder(100);
StringBuilder sb = new StringBuilder();
try {
sURL.append("http://example.com/");
InputStream is = new URL(sURL.toString()).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
} catch (MalformedURLException me) {
System.out.println("## MalformedURLException occured" + me.getMessage());
} catch (UnsupportedEncodingException me) {
System.out.println("## UnsupportedEncodingException occured : " + me.getMessage());
} catch (IOException me) {
System.out.println("## IOException occured in : " + me.getMessage());
} catch (Exception me) {
System.out.println("## Exception occured : " + me.getMessage());
}
return sb1.toString();
}
答案 2 :(得分:0)
您可能想要使用Apache HttpClient实用程序。
添加以下maven依赖项:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
接下来,使用以下代码使用HTTP Get方法点击URL。
//create the url
String url = "http://www.google.com/search?q=httpClient";
//create the http client object
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
//execute the request and capture the response
HttpResponse response = client.execute(request);
//get response code
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
//get the response body
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
//capture the response in string
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
如果网址已关闭,HttpClient会自动重试点击网址。此外,它还提供了重试事件处理程序。