public void GetHtml()
{
/*宣告網址字串*/
String uriAPI = "http://www.google.com";
/*建立HTTP Get連線*/
HttpGet httpRequest = new HttpGet(uriAPI);
//HttpPost httpRequest = new HttpGet(uriAPI); //改用post
try
{
/*發出HTTP request*/
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
/*若狀態碼為200 ok*/
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
/*取出回應字串*/
String strResult = EntityUtils.toString(httpResponse.getEntity());//UTF-8可以判斷
//String strResult = EntityUtils.toString(httpResponse.getEntity(),"utf-8");//utf-8要自己判斷
/*刪除多餘字元*/
//mTextView1.setText(strResult);
}
else
{
//mTextView1.setText("Error Response: "+httpResponse.getStatusLine().toString());
}
}
catch (ClientProtocolException e)
{
//mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (IOException e)
{
//mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (Exception e)
{
//mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
}
-------------------------------------------傳送參數進網站
public void PostGetHtml()
{
/*宣告網址字串*/
String uriAPI = "http://www.google.com";
/*建立HTTP Post連線*/
HttpPost httpRequest = new HttpPost(uriAPI);
/*
* Post運作傳送變數必須用NameValuePair[]陣列儲存
*/
List <NameValuePair> params = new ArrayList <NameValuePair>();
params.add(new BasicNameValuePair("str", "I am Post String"));
try
{
/*發出HTTP request*/
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
/*取得HTTP response*/
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
/*若狀態碼為200 ok*/
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
/*取出回應字串*/
String strResult = EntityUtils.toString(httpResponse.getEntity());
mTextView1.setText(strResult);
}
else
{
mTextView1.setText("Error Response: "+httpResponse.getStatusLine().toString());
}
}
catch (ClientProtocolException e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (IOException e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (Exception e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
}
沒有留言:
張貼留言