通过Map和url向第三方服务器发送post表单请求

    public static String postWithParamsForString(String url,Map map){
List params = new ArrayList();
        Set set = map.keySet();
        Iterator it = set.iterator();
        while(it.hasNext())
        {
            String key = it.next();
            NameValuePair pair = new BasicNameValuePair(key, String.valueOf(map1.get(key)));
            params.add(pair);
        }
        
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost =   new HttpPost(url);
        String s = "";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            HttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                HttpEntity entity = response.getEntity();
                s = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

如果需要对象转Map

    public Map map(Object o) throws IllegalAccessException, NoSuchFieldException {
        Map map = new HashMap();

        Field[] fields = o.getClass().getDeclaredFields();

        for(int i = 0; i < fields.length; i++){
            Field field = o.getClass().getDeclaredField(fields[i].getName());
            field.setAccessible(true);
            Object value = field.get(o);

            if(!TextUtils.isEmpty(value)){
                map.put(fields[i].getName(), value);
            }
        }
        return map;
    }

你可能感兴趣的:(java)