0

我想发送一个 http 请求并从该请求中获取一个字符串。

我目前正在使用此代码,但无论我的 URL 是什么,我总是得到空值。有什么问题?

try { // 为所需页面创建一个 URL 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) { }
4

3 回答 3

0

试试这个

URL url = new URL("http://whatever");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
//read stream here    
于 2012-10-16T16:27:33.097 回答
0
                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();

尝试从此代码中使用

于 2012-10-16T16:29:01.007 回答
0

这对我有用:

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();
        }
于 2012-10-16T18:09:07.497 回答