Android getting text from a URL always NULL
-
07-07-2021 - |
문제
I'd like to send an http request and get a string back from that request.
I am currently using this code, but no matter what my URL is, I always get null. What's the issue?
try { // Create a URL for the desired page URL url = new URL("http://hostname:80/index.html");
// Read all the text returned by the server BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { // str is one line of text; readLine() strips the newline character(s) } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { }
해결책
String URL = "http://hostname:80/index.html"
String XML = stringWriter.toString();
// System.out.println(XML);
se = new StringEntity(XML, "UTF-8");
se.setContentType("text/xml;charset=UTF-8");
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
try use from this code
다른 팁
Try this
URL url = new URL("http://whatever");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
//read stream here
This is working for me:
httpClient = AndroidHttpClient.newInstance("Android");
String url = "Your URL";
try{
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ //Don't know what string you are waiting for
//do something
}
}
catch(IOException e){
httpClient.close();
}
제휴하지 않습니다 StackOverflow