标签:httpclient httpurlconnection httppost httpget httpeneity
public static String getData() throws Exception{
try {
//HttpPath.GetGamesPath() : 网络请求路径
URL url=new URL(HttpPath.GetGamesPath());
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
InputStream ips=conn.getInputStream();
byte[] data=read(ips);
String str=new String(data);
System.out.println(str);
return str;
}else{
return "网络错误 :conn.getResponseCode() ="+conn.getResponseCode();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
return "HttpService.getGamesData()发生异常! "+e.getMessage();
}
}
/*
* 读取流中的数据
* */
public static byte[] read(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len=0;
while((len=inStream.read(buffer))!=-1){
outStream.write(buffer,0,len);
}
inStream.close();
return outStream.toByteArray();
}/**
* httpclient post提交数据
* @param parameters
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String toPostdata(List<BasicNameValuePair> parameters) throws ClientProtocolException, IOException{
String str="获取失败";
//初始化
HttpClient client=new DefaultHttpClient();
//HttpPath.GetGamesPath() : 网络请求路径
HttpPost httpPost=new HttpPost(HttpPath.GetGamesPath());
//设置参数
UrlEncodedFormEntity params=new UrlEncodedFormEntity(parameters,"UTF-8");
httpPost.setEntity(params);
//执行请求
HttpResponse response= client.execute(httpPost);
//取得返回值
if(response.getStatusLine().getStatusCode()==200){
//请求成功
HttpEntity entity=response.getEntity();
str=EntityUtils.toString(entity, "UTF-8");
}
return str;
}
/**
* httpclient get 获得数据
* @return
*/
public static String toGetData(){
String str="获取数据失败";
HttpClient client=new DefaultHttpClient();
////HttpPath.GetGamesPath() : 网络请求路径
HttpGet get=new HttpGet(HttpPath.GetGamesPath());
try {
HttpResponse httpResponse=client.execute(get);
if(httpResponse.getStatusLine().getStatusCode()==200){
str=EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
}
return str;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
return "toGetData 异常:"+e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
return "toGetData 异常:"+e.getMessage();
}
}版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:httpclient httpurlconnection httppost httpget httpeneity
原文地址:http://blog.csdn.net/lablenet/article/details/47663153