HttpClient 使用


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;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章