Http連接GET/POST請求

創建步驟:
  1、創建HttpGet(或HttpPost)對象,將要請求的URL通過構造方法傳入HttpGet(或HttpPost)對象中;
   2、使用DefaultHttpClient類的execute方法發送HTTP GET或HTTP POST 請求,並返回HttpResponse對象;
   3、通過HttpResponse接口的getEntity方法返回響應信息。
Http連接POST請求
// 第一步,創建HttpPost對象
HttpPost httpPost = new HttpPost(url);
// 設置HTTP POST請求參數必須用NameValuePair對象
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("bookname", "2465158248"));
System.out.println("result1");         
// 設置httpPost請求參數         
try        
{             
	httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
	// 第二步,使用execute方法發送HTTP GET請求,並返回HttpResponse對象
	HttpResponse httpResponse;             
	try            
	{                 
		httpResponse = new DefaultHttpClient().execute(httpPost);
		System.out.println("result");
		if (httpResponse.getStatusLine().getStatusCode() == 200)
		{                     
		// 第三步,使用getEntity方法活得返回結果
		String result = EntityUtils.toString(httpResponse.getEntity());
		System.out.println("result" + result);
	}
	}
	catch (ClientProtocolException e)
	{                 
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	catch (IOException e)
	{
	// TODO Auto-generated catch block
	e.printStackTrace();
	}
}
catch (UnsupportedEncodingException e)
{
	e.printStackTrace();
}
}

Http連接GET請求
String url;
//第一步,創建HttpGet對象
HttpGet httpGet = new HttpGet(url);
//第二步,使用execute方法發送HTTP GET請求,並返回HttpResponse對象
httpResponse = new DefaultHttpClient().execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200)
{        
	//第三步,使用getEntity方法活得返回結果
	String result = EntityUtils.toString(httpResponse.getEntity());
}




發佈了57 篇原創文章 · 獲贊 7 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章