之前在Android中,已经实现了GET请求,能抓取网页了:
且已经实现了对应字符编码解码为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;
}然后有待后续测试。
因为暂时,去运行的时候,结果出错,折腾过程参见:
2.
【总结】
转载请注明:在路上 » 【记录】Android中利用HttpClient实现POST请求