如下,給出HTTP通信的主要代碼:
一.post方式通信
主要分爲以下幾步:
1.新建Httppost對象;
2.爲Httppost設置參數和編碼格式;
3.新建HttpClient對象;
4.新建Httpresponse對象;(HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest); )//可以這樣一部搞定。
這樣就差不多完成了。
Httppost httpRequest = new Httppost(UEL); //此處URL未給出,可自己定義
try {
//設置編碼格式 ,請求參數
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//提交HttpPost對象和獲取服務器HttpResponse響應數據完
HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode()==200){
String result = EntityUtils.toString(httpResponse.getEntity());
System.out.println(result);
}
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
二.另外一種是GET方法。
//創建HttpGet對象。
HttpGet get = new HttpGet(url);
//發送GEt請求
HttpResponse httpResponse = httpClient.execute(get);
//如果服務器成功返回響應
if(){ //如上一種方法之if代碼。
}