最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【记录】Android中利用HttpClient实现POST请求

Android crifan 3090浏览 0评论

之前在Android中,已经实现了GET请求,能抓取网页了:

【已解决】Android中如何用代码实现去抓取网页

且已经实现了对应字符编码解码为Unicode了:

【已解决】Android中,如何对某个编码(如GB2312)的字符串进行解码为Unicode字符

现在继续去实现对应的HttpClient的POST操作。


1.参考:

Android用Apache HttpClient 实现POST和Get请求

Android入门:用HttpClient模拟HTTP的GET和POST请求

android HttpClient post get

Android使用httpClient进行Post和Get发送参数

 

去写代码:

    
    /** Get response html from url and designated html charset and headerDict, postDict */
    public String getUrlRespHtml(String url,
    							HttpParams headerParams, 
								String htmlCharset, 
								List<NameValuePair> postDict)
    {
    	// init
    	String respHtml = "";
    	String defaultCharset = "UTF-8";
    	// check para
    	if(htmlCharset == "")
    	{
    		htmlCharset = defaultCharset;
    	}
    	
    	//init 
    	HttpClient httpClient = new DefaultHttpClient();
    	HttpUriRequest request;
    	HttpResponse response;
    	
    	if(postDict != null)
    	{
    		HttpPost postReq = new HttpPost(url);
    		
    		try{
    			HttpEntity postBodyEnt = new UrlEncodedFormEntity(postDict);
    			postReq.setEntity(postBodyEnt);
    		}
    		catch(Exception e){
    			
    		}
    		
    		request = postReq;
    	}
    	else
    	{
        	HttpGet getReq = new HttpGet(url);
        	
        	request = getReq;
    	}
    	
    	if(headerParams != null)
    	{
    		request.setParams(headerParams);
    	}
    	
		try{
			response = httpClient.execute(request);
	        
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
	        	respHtml = EntityUtils.toString(response.getEntity(), htmlCharset);
	        }
	        
        } catch (ClientProtocolException cpe) {
            // TODO Auto-generated catch block
        	cpe.printStackTrace();    
        } catch (IOException ioe) {
            // TODO Auto-generated catch block
        	ioe.printStackTrace();
        }
		
    	return respHtml;
    }

然后有待后续测试。

因为暂时,去运行的时候,结果出错,折腾过程参见:

【已解决】ADT中运行Android程序出错:An internal error occurred during: "Launching New_configuration". Path for project must have only one segment.

 

2.

 

【总结】

转载请注明:在路上 » 【记录】Android中利用HttpClient实现POST请求

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.149 seconds, using 22.13MB memory