您的位置:首页 > 理论基础 > 计算机网络

HttpClient 使用

2014-04-09 14:09 821 查看
public static String inStream2String(InputStream is) throws Exception
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = -1;
while ((len = is.read(buf)) != -1)
{
baos.write(buf, 0, len);
}
return new String(baos.toByteArray());
}

/**第三方网络访问组件 get请求

*/
public static String getHttpClient(String urlString)
{

String resultString = "";
DebugHelper.i(TAG, urlString);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(urlString);
try
{
HttpResponse response = client.execute(get);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
InputStream is = response.getEntity().getContent();
resultString = HttpServer.inStream2String(is);
DebugHelper.i(TAG, "resultString:" + resultString);
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
return resultString;
}

/**第三方网络访问组件 post请求

List <NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("str", "I am Post String"));
*/
public static String postHttpClient(String urlString,
List<NameValuePair> params)
{

String resultString = "";
DebugHelper.i(TAG, urlString);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
//post.setHeader("Content-Type",
//"application/x-www-form-urlencoded; charset=utf-8");
try
{

if (PingGuApplication.isDebug)
{
for (int i = 0; i < params.size(); i++)
{
DebugHelper.i(TAG, "Name:" + params.get(i).getName()
+ " Value:" + params.get(i).getValue());
}
}
//UrlEncodedFormEntity urlEncodedFormEntity=new UrlEncodedFormEntity(params, HTTP.UTF_8);

post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
//post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
InputStream is = response.getEntity().getContent();
resultString = inStream2String(is);
DebugHelper.i(TAG, "resultString:" + resultString);
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
return resultString;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HttpClient