Android POST和GET请求
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2016-07-13 08:35:55
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
/** * GET请求 * */ protected String getUrlPage(String url){ String uriAPI = url; HttpGet httpRequest = new HttpGet(uriAPI); try { HttpResponse httpResponse = new DefaultHttpClient() .execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == 200) { String strResult = EntityUtils.toString(httpResponse .getEntity()); //替换掉空行 // strResult = eregi_replace("(\r\n|\r|\n|\n\r)", "",strResult); return strResult; } else { return "Error Response: "+ httpResponse.getStatusLine().toString(); } } catch (ClientProtocolException e) { e.printStackTrace(); return e.getMessage().toString(); } catch (IOException e) { e.printStackTrace(); return e.getMessage().toString(); } catch (Exception e) { e.printStackTrace(); return e.getMessage().toString(); } } /** * POST请求 * 添加参数方法如下 * List<NameValuePair> params = new ArrayList<NameValuePair>(); * params.add(new BasicNameValuePair("action", "downloadAndroidApp")); * */ private String postUrl(String uri,List<NameValuePair> params){ String reStr=""; // 第一步,创建HttpPost对象 HttpPost httpPost = new HttpPost(uri); HttpResponse httpResponse = null; try { // 设置httpPost请求参数 httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); httpResponse = new DefaultHttpClient().execute(httpPost); //System.out.println(httpResponse.getStatusLine().getStatusCode()); if (httpResponse.getStatusLine().getStatusCode() == 200) { // 第三步,使用getEntity方法活得返回结果 reStr= EntityUtils.toString(httpResponse.getEntity()); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return reStr; }