HTTP connection in Android

2019-07-29 13:38发布

How to create an Http Connection to retrive a web page content to my android? Please post example code for this.

标签: android http
1条回答
看我几分像从前
2楼-- · 2019-07-29 13:58

Its http client,get example it might help

    HttpClient client;
    HttpGet method;
    String url;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    url="enter your url here";
    method = new HttpGet(url);
    try {
            client.execute(method);


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
           setContentView(R.layout.main);
}
public void executeHttpGet() throws Exception {
    BufferedReader in = null;
    try {
        client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(url));
        HttpResponse response = client.execute(method);
        in = new BufferedReader
        (new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        String page = sb.toString();
        System.out.println(page);
        } finally {
        if (in != null) {
            try {
                in.close();
                } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

it access XML data in preview i have this example try.

查看更多
登录 后发表回答