用HttpClient处理Http请求

处理GET请求:

StringBuffer sb = new StringBuffer();
    		
HttpClient httpClient = new DefaultHttpClient();
HttpParams httpParams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);

//当参数值包含中文时,需要用URLEncoder类对参数值进行编码处理
HttpResponse response = httpClient.execute(new HttpGet(url));

if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
	HttpEntity entity = response.getEntity();
	if(entity!=null){
		BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
		String line = null;
		while((line=reader.readLine())!=null){
			sb.append(line + "\n");
		}
		reader.close();
	}
}

  

处理Post请求:

StringBuffer sb = new StringBuffer();
    		
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

//post方式时,需要用NameValuePair数组传递参数
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  

nameValuePairs.add(new BasicNameValuePair("username", "cjm陈"));  
nameValuePairs.add(new BasicNameValuePair("password", "123"));  

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));  

HttpResponse response = httpClient.execute(httpPost); 

if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
	HttpEntity entity = response.getEntity();
	if(entity!=null){
		BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
		String line = null;
		while((line=reader.readLine())!=null){
			sb.append(line + "\n");
		}
		reader.close();
	}
}

 

你可能感兴趣的:(httpclient)