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;

}

 

你可能感兴趣的:(android,String,null,application,url,input)