我尝试从Android应用程序中使用Web服务休息,但是当我查找示例时,发现只有两种方法,httpClient已被弃用,我甚至无法为我的应用程序导入它的版本,而且,方法使用HttpURLConnection,它不会像预期的那样工作。
我的代码就在这一刻:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class RestConnect {
public static String listar() throws IOException {
try {
URL reqURL = new URL("http://localhost/wsRest/index.php/contact");
HttpURLConnection request = (HttpURLConnection) (reqURL.openConnection());
request.setRequestMethod("GET");
request.connect();
} catch (Exception e) {
return "Nope!";
}
return "YESSSS!";
}
}
如何访问我的网址并轻松获取内容,即Get和Post方法?
非常感谢大家!
答案 0 :(得分:1)
答案 1 :(得分:1)
试试这个
URL url = new URL(urlpath.toString()); // Your given URL.
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}