开发者

Android webrequest simple solution

开发者 https://www.devze.com 2023-04-02 03:59 出处:网络
I want to connect to a web-server (a page) via a simple URL which already con开发者_如何学Ctains any parameters I want to sent, like : www.web-site.com/action.php/userid/42/secondpara/23/ and then get

I want to connect to a web-server (a page) via a simple URL which already con开发者_如何学Ctains any parameters I want to sent, like : www.web-site.com/action.php/userid/42/secondpara/23/ and then get the page content which is generated by the site (won't be morde than a simple OK/NOK). How can I manage to do this? I failed to find any example-code or documentation which seems to fit my problem.

Thx for helping.


try this:

public static void connect(String url)
{

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        Log.i("Praeda",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
        }


    } catch (Exception e) {}
}

    private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号