1 package com.foxinmy.weixin4j.http.entity; 2 3 import java.util.Iterator; 4 import java.util.List; 5 import java.util.Map; 6 import java.util.Map.Entry; 7 8 import com.foxinmy.weixin4j.http.ContentType; 9 import com.foxinmy.weixin4j.http.URLParameter; 10 import com.foxinmy.weixin4j.util.Consts; 11 import com.foxinmy.weixin4j.util.URLEncodingUtil; 12 13 public class FormUrlEntity extends StringEntity { 14 15 private static final String PARAMETER_SEPARATOR = "&"; 16 17 public FormUrlEntity(List<URLParameter> parameters) { 18 super(formatParameters(parameters), 19 ContentType.APPLICATION_FORM_URLENCODED); 20 } 21 22 public FormUrlEntity(Map<String, String> parameters) { 23 super(formatParameters(parameters), 24 ContentType.APPLICATION_FORM_URLENCODED); 25 } 26 27 public static String formatParameters(List<URLParameter> parameters) { 28 StringBuilder body = new StringBuilder(); 29 URLParameter parameter = parameters.get(0); 30 body.append(parameter.encoding()); 31 for (int i = 1; i < parameters.size(); i++) { 32 body.append(PARAMETER_SEPARATOR); 33 parameter = parameters.get(i); 34 body.append(parameter.encoding()); 35 } 36 return body.toString(); 37 } 38 39 public static String formatParameters(Map<String, String> parameters) { 40 StringBuilder body = new StringBuilder(); 41 Iterator<Entry<String, String>> it = parameters.entrySet().iterator(); 42 it.hasNext(); 43 Entry<String, String> parameter = it.next(); 44 body.append(String.format("%s=%s", URLEncodingUtil.encoding( 45 parameter.getKey(), Consts.UTF_8, true), URLEncodingUtil 46 .encoding(parameter.getValue(), Consts.UTF_8, true))); 47 while (it.hasNext()) { 48 parameter = it.next(); 49 body.append(PARAMETER_SEPARATOR).append( 50 String.format("%s=%s", URLEncodingUtil.encoding( 51 parameter.getKey(), Consts.UTF_8, true), 52 URLEncodingUtil.encoding(parameter.getValue(), 53 Consts.UTF_8, true))); 54 } 55 return body.toString(); 56 } 57 }