I trying to consume a webservice rest from and Android app, but when I look for examples and found only two ways, with httpClient which is deprecated and I can't even import for my application for it version, and, a method with HttpURLConnection which, doesn't work like expected.
My code right in this moment:
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!";
}
}
How can I access my URL and easily get it content, which Get and Post methods?
Much thanks everyone!
Better use awesome http library https://github.com/square/okhttp
For example, try this snippet:
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
try this
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.