Home | History | Annotate | Download | only in httpclient
      1 package org.robolectric.shadows.httpclient;
      2 
      3 import android.net.Uri;
      4 import java.io.IOException;
      5 import java.util.LinkedHashMap;
      6 import java.util.List;
      7 import java.util.Map;
      8 import java.util.Set;
      9 import org.apache.http.HttpEntity;
     10 import org.apache.http.HttpRequest;
     11 import org.apache.http.NameValuePair;
     12 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
     13 import org.apache.http.client.methods.HttpGet;
     14 import org.apache.http.client.utils.URLEncodedUtils;
     15 
     16 public class ParamsParser {
     17 
     18   public static Map<String, String> parseParams(HttpRequest request) {
     19     if (request instanceof HttpGet) {
     20       return parseParamsForGet(request);
     21     }
     22     if (request instanceof HttpEntityEnclosingRequestBase) {
     23       return parseParamsForRequestWithEntity((HttpEntityEnclosingRequestBase) request);
     24     }
     25     return new LinkedHashMap<>();
     26   }
     27 
     28   private static Map<String, String> parseParamsForRequestWithEntity(HttpEntityEnclosingRequestBase request) {
     29     try {
     30       LinkedHashMap<String, String> map = new LinkedHashMap<>();
     31       HttpEntity entity = request.getEntity();
     32       if (entity != null) {
     33         List<NameValuePair> pairs = URLEncodedUtils.parse(entity);
     34 
     35         for (NameValuePair pair : pairs) {
     36           map.put(pair.getName(), pair.getValue());
     37         }
     38       }
     39       return map;
     40     } catch (IOException e) {
     41       throw new RuntimeException(e);
     42     }
     43   }
     44 
     45   private static Map<String, String> parseParamsForGet(HttpRequest request) {
     46     Uri uri = Uri.parse(request.getRequestLine().getUri());
     47     Set<String> paramNames = uri.getQueryParameterNames();
     48     LinkedHashMap<String, String> map = new LinkedHashMap<>();
     49     for (String paramName : paramNames) {
     50       map.put(paramName, uri.getQueryParameter(paramName));
     51     }
     52     return map;
     53   }
     54 }
     55