android通过HttpClient与服务器JSON交互

通过昨天对HttpClient的学习,今天封装了HttpClient类

代码如下:

package com.tp.soft.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class HttpUtil {
    public static String postRequest(String serverPath, Map<String, String> params, String encoding){
        List<NameValuePair> paramPair = new ArrayList<NameValuePair>();
        if(params != null && !params.isEmpty()){
            for(Map.Entry<String, String> entry : params.entrySet()){
                paramPair.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(serverPath);
            post.setEntity(new UrlEncodedFormEntity(paramPair, HTTP.UTF_8));
            HttpResponse response = client.execute(post);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                //数据
                String reqData = null;
                String responseData = "";
                while((reqData = br.readLine()) != null){
                    responseData += reqData;
                }
                br.close();
                return responseData;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "postRequest error";
    }
}

然后通过调用HttpUtil类来达成与服务器交互

package com.tp.soft.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tp.soft.entity.User;
import com.tp.soft.util.HttpUtil;

public class MainActivity extends Activity {
    
    private ListView mListView;
    private TextView mContentTxt;
    private TextView mTimeTxt;
    
    private String serverPath = "http://122.226.178.54:8080/uploadApp/LoginServlet";
    private static final String ENCODING = "utf-8";
    private List<User> userList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        loadList();
         mListView = (ListView) findViewById(R.id.list_id);
        mListView.setAdapter(new BaseAdapter() {
            
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if(null == convertView){
                    convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null);
                }
                
                TextView textView = (TextView) convertView.findViewById(R.id.contentTxt);
                textView.setText(userList.get(position).getUsername());
                return convertView;
            }
            
            @Override
            public long getItemId(int position) {
                return position;
            }
            
            @Override
            public Object getItem(int position) {
                return position;
            }
            
            @Override
            public int getCount() {
                return userList.size();
            }
        });
    }

    private List<User> loadList() {
        Map<String, String> params = new HashMap<String, String>();
        String data = HttpUtil.postRequest(serverPath, params, ENCODING);
        userList = new Gson().fromJson(data, new TypeToken<List<User>>() {}.getType());    
        return userList;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

服务器端则采用了servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        
        PrintWriter pw = response.getWriter();
        Gson gson = new GsonBuilder().create();
        List<User> userList = new ArrayList<User>();
        User user = new User();
        user.setUsername("zs");
        user.setPassword("1");
        userList.add(user);
        
        User user1 = new User();
        user1.setUsername("lisi");
        user1.setPassword("2");
        userList.add(user1);
        String json = gson.toJson(userList);
        pw.print(json);
    }

 

android通过HttpClient与服务器JSON交互,布布扣,bubuko.com

android通过HttpClient与服务器JSON交互

上一篇:安卓平台多语言的简单实现


下一篇:【转】How to view word document in WPF application