Android连网Get、Post和HttpURLConnection

 

需要注意的是如果将配置文件中的权限写在<Application>节点中则系统仍然会报Permission denied的错误。

 

public String getDataByHttpGet(String httpUrl)

{

String result = null;

HttpGet httpGet = new HttpGet(httpUrl);

HttpClient httpClient = new DefaultHttpClient();

try {

HttpResponse httpResponse = httpClient.execute(httpGet);

if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)

{

result = EntityUtils.toString(httpResponse.getEntity());

Log.v("HttpGet", result);

}

else

{

Log.v("HttpGet", "HttpGet has exception.");

}

} catch (ClientProtocolException e) {

// TODO Auto-generated cat7ch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return result;

}

public String getDataByHttpPost(String httpUrl)

{

String result = null;

HttpPost httpPost = new HttpPost(httpUrl);

List<NameValuePair> params = new ArrayList<NameValuePair>();

params.add(new BasicNameValuePair("par", "request-post"));

try {

HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");

httpPost.setEntity(entity);

HttpClient httpClient = new DefaultHttpClient();

HttpResponse response = httpClient.execute(httpPost);

int code = response.getStatusLine().getStatusCode();

if( code == HttpStatus.SC_OK)

{

result = EntityUtils.toString(response.getEntity());

Log.v("HttpGet", result);

}

else

{

Log.v("HttpGet", "HttpGet has exception.");

}

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return result;

}

public String Refesh(String httpUrl)

{

String result = null;

try {

URL url = new URL(httpUrl);

HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();

urlConn.connect();

InputStream input = urlConn.getInputStream();

InputStreamReader inputReader = new InputStreamReader(input);

BufferedReader reader = new BufferedReader(inputReader);

String str = null;

StringBuffer sb = new StringBuffer();

while((str = reader.readLine())!=null)

{

sb.append(str).append("/n");

}

result = sb.toString();

} catch (MalformedURLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return result;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

L_serein

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值