【工具类】NetWorkHelper

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.util.Log;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.protocol.HTTP;

import org.apache.http.util.EntityUtils;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.util.List;





public class NetWorkHelper {

    

    //  使用POST方式时,传递参数必须使用NameValuePair数组

    //  通过setEntity方法来发送HTTP请求

    //  通过DefaultHttpClient 的 execute方法来获取HttpResponse

    //  通过getEntity()从Response中获取内容

    public static String getPostFromWeb(String path,List<NameValuePair> nameValuePairs) {

        try{

              String datatext = null;

              HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(path);

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));

            HttpResponse response = httpclient.execute(httppost);

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

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

            Log.i("httpPostData", "data:"+ datatext);

            Log.i("httpPostData", "得到状态码:"+ statusCode);

            return datatext;

        }catch(Exception e){

            Log.i("httpPostData", "Exception:"+ e.getMessage());

                e.printStackTrace();

        }

         return null;

    }

    

    /**

     * 通过地址得到网络图片

     * @param url

     * @return

     */

    public static Bitmap getHttpBitmap(String url) {

        URL fileUrl = null;

        Bitmap bitmap = null;

        try {

            fileUrl = new URL(url);

            HttpURLConnection urlconn = (HttpURLConnection) fileUrl.openConnection();

            urlconn.setConnectTimeout(0);

            urlconn.setDoInput(true);

            urlconn.connect();

            InputStream input = urlconn.getInputStream();

            bitmap = BitmapFactory.decodeStream(input);

            input.close();

        } catch (MalformedURLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return bitmap;

    }

}

 

你可能感兴趣的:(NetWork)