2012年5月2日 星期三

在Android使用httpclient傳值讀值

在使用httpclient必需先去 這裡下載 java jar

我是使用HttpClient 4.1.3 (GA) 這個版本

首先先說明如何讀取HTML
public static String getHtmlContent(final String url) {
    String result="";
    HttpGet httpRequest = new HttpGet(url);
    HttpClient httpclient = new DefaultHttpClient();

    try {
        HttpResponse httpResponse = httpclient.execute(httpRequest);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            result = EntityUtils.toString(httpResponse.getEntity());
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return result;
}

傳入URL後就會讀取HTML

如果要比對字串,會多一個字元,我不知道是不是因為我用PHP的echo的關係
在比對時要再後面多加一個 "\n"

在來是POST資料到指定的網址,並回傳字串
public static String postData(String url, List<NameValuePair> params) {
    String result="";
    HttpPost httpRequest = new HttpPost(url);
    try {
        httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
        HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
        
        if(httpResponse.getStatusLine().getStatusCode() == 200){
            result = EntityUtils.toString(httpResponse.getEntity());
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return result;
}

不過在使用這函式時要配合使用
List<NameValuePair> params= new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("data","1234567"));
params.add(new BasicNameValuePair("data1","000000"));
postData("http://iccl.nkmu.edu.tw/WSN/getData.php", params)

如果有兩個值就要像上面那樣add兩次,以此類推