这里只介绍如何使用HttpClient发起GET或者POST请求
GET 方式
- //先将参数放入List,再对参数进行URL编码
- List<BasicNameValuePair>params=newLinkedList<BasicNameValuePair>();
- params.add(newBasicNameValuePair("param1","中国"));
- params.add(newBasicNameValuePair("param2","value2"));
- //对参数编码
- Stringparam=URLEncodedUtils.format(params,"UTF-8");
- //baseUrl
- StringbaseUrl="http://ubs.free4lab.com/php/method.php";
- //将URL与参数拼接
- HttpGetgetMethod=newHttpGet(baseUrl+"?"+param);
- HttpClienthttpClient=newDefaultHttpClient();
- try{
- HttpResponseresponse=httpClient.execute(getMethod);//发起GET请求
- Log.i(TAG,"resCode="+response.getStatusLine().getStatusCode());//获取响应码
- Log.i(TAG,"result="+EntityUtils.toString(response.getEntity(),"utf-8"));//获取服务器响应内容
- }catch(ClientProtocolExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }catch(IOExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }
POST方式
- //和GET方式一样,先将参数放入List
- params=newLinkedList<BasicNameValuePair>();
- params.add(newBasicNameValuePair("param1","Post方法"));
- params.add(newBasicNameValuePair("param2","第二个参数"));
- try{
- HttpPostpostMethod=newHttpPost(baseUrl);
- postMethod.setEntity(newUrlEncodedFormEntity(params,"utf-8"));//将参数填入POSTEntity中
- HttpResponseresponse=httpClient.execute(postMethod);//执行POST方法
- Log.i(TAG,"resCode="+response.getStatusLine().getStatusCode());//获取响应码
- Log.i(TAG,"result="+EntityUtils.toString(response.getEntity(),"utf-8"));//获取响应内容
- }catch(UnsupportedEncodingExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }catch(ClientProtocolExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }catch(IOExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }
本文介绍了如何利用Java中的HttpClient发起GET和POST请求的方法。包括了参数的构造、URL编码、请求的发送及响应结果的处理等关键步骤。

5258

被折叠的 条评论
为什么被折叠?



