問題
在對接第三方的請求接口時(shí),POST傳參要求的格式類似GET的params;
請求內(nèi)容類型,這里為 application/x-www-form-urlencoded
標(biāo)準(zhǔn)的編碼格式,數(shù)據(jù)被編碼為名稱/值對。
username=username&password=password&type=1&type=2
問題解析
- 方法一: 將對象轉(zhuǎn)為List<NameValue>的list,用HttpPost請求類時(shí),可將list轉(zhuǎn)為JsonString放入entity. 具體方式請查看此例
- 方法二: 將對象轉(zhuǎn)為 username=username&password=password&type=1&type=2 格式.在此方法中重寫了方法類的toString();
public String toString() {
String s = "";
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
s += field.getName()+"="+field.get(this).toString()+"&";
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
測試Demo如下
public class TestDemo {
public static void main(String[] args) {
Test test = new Test("zhangsan","123456","2");
System.out.println("test.toString() = " + test.toString());
}
static class Test{
private String username;
private String password;
private String type;
public Test(String username, String password, String type) {
this.username = username;
this.password = password;
this.type = type;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
String s = "";
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
s += field.getName()+"="+field.get(this).toString()+"&";
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return s;
}
}
}
測試結(jié)果如下

測試結(jié)果