问题
I have a problem to get a web page content in my Android App. I would like to read the contents from this address https://szr.szczecin.pl/utms/data/layers/VMSPublic .
At first I tried to do it in Java using this code:
public class Main {
public static void main(String[] args) {
String https_url = "https://szr.szczecin.pl/utms/data/layers/VMSPublic";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
print_content(con);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void print_content(HttpsURLConnection con) {
if (con != null) {
try {
System.out.println("****** Content of the URL ********");
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String input;
while ((input = br.readLine()) != null) {
System.out.println(input);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
It worked after I downloaded and installed the certificate from that webpage. How can I do the same in Android? I tried HTTPSURLConnection in Android but it returns me only the address of the web page. When I was trying HTTPURLConnection it gives me an information that document was moved (status 302).
回答1:
You can try following code:
public static String getResponseFromUrl(String url) {
HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet(URL); // Set the action you want to do
HttpResponse response = httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line);
String resString = sb.toString();
is.close();
return resString;
}
回答2:
Are you trying to set target sdk as 23 in your app which is using Apache HttpClient for all the network related operations? If yes, here is a bad news. Android 6.0 (API Level 23) release removes support for the Apache HTTP client. Hence you can not use this library directly in API 23. But there is a way to use it. Add useLibrary ‘org.apache.http.legacy’ in your build.gradle file as below-
android {
useLibrary 'org.apache.http.legacy'
}
If this does not work you may apply the following hack-
– Copy org.apache.http.legacy.jar which is in /platforms/android-23/optional path of your Android SDK directory to your project’s app/libs folder.
– Now Add compile files(‘libs/org.apache.http.legacy.jar’) inside dependencies{} section of build.gradle file.
来源:https://stackoverflow.com/questions/22170470/how-to-get-a-web-page-content-in-android