我正在努力寻找已弃用的DefaultHttpClient
和已联系的类HttpPost
等的替代品。
第一次尝试时,我尝试使用volley
库,但似乎没有任何效果,所以经过一些研究后我现在正在尝试使用Retrofit 1.9
。
在我的应用中,我连接到一个自己的宁静客户端。这是旧代码(示例POST),它运行得非常好:
private static DefaultHttpClient httpClient = new DefaultHttpClient();
public static String executePOST(Map<String, String> postParams, int connTO, int sockTO, String uri){
String res, message;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, connTO);
HttpConnectionParams.setSoTimeout(httpParams, sockTO);
HttpConnectionParams.setTcpNoDelay(httpParams, true);
httpClient.setParams(httpParams);
HttpPost httppost = new HttpPost(uri);
JSONObject json = new JSONObject();
try {
Iterator<Entry<String, String>> iterator = postParams.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> pair = (Map.Entry<String, String>)iterator.next();
json.put(pair.getKey(), pair.getValue());
}
message = json.toString();
httppost.setEntity(new StringEntity(message, "UTF8"));
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
res = EntityUtils.toString(entity).trim();
} catch (ClientProtocolException e) {
res = "Client Protocol Exception";
} catch (IOException e) {
res = e.getLocalizedMessage();
} catch (JSONException e){
res = e.getLocalizedMessage();
}
return res;
}
我从我的活动
发送这样的请求Map<String, String> arguments = new HashMap<String, String>();
arguments.put("email", username);
new HttpClient(arguments, new LoginActivityCommunicationListener(this, LoginOperation.EMAIL_CHECK), URI_ROOT + "/kunde", 0).execute();
参数中的侦听器处理响应回调,0
表示POST。
这会产生JSON响应,包含字段id
和person
所以我尝试像这样实现上面的Retrofit变种
MyApi.java
public interface MyDosAPI {
@FormUrlEncoded
@POST("/kunde")
public void checkEmail(@Field("email") String email, Callback<EmailCheck> response);
}
EmailCheck.java
public class EmailCheck {
@SerializedName("id")
private String id;
@SerializedName("person")
private String person;
public void setId(String id){
this.id = id;
}
public void setPerson(String person){
this.person = person;
}
public String getId(){
return id;
}
public String getPerson(){
return person;
}
}
并在活动中
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(URI_ROOT)
.build();
MyDosAPI api = adapter.create(MyDosAPI.class);
api.checkEmail(username, new Callback<EmailCheck>() {
@Override
public void success(EmailCheck emailChecks, Response response) {
Log.i("MyCount", "success");
}
@Override
public void failure(RetrofitError error) {
Log.i("MyCount", error.getMessage());
}
});
结果
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
显然,我缺少一些必不可少的东西。是否 - 除了Retrofit或Volley之外 - 我可以像以前一样定义请求的另一个解决方案?
答案 0 :(得分:0)
更改为:
public interface MyDosAPI {
@POST("/kunde")
public void checkEmail(@Body String email, Callback<EmailCheck> response);
}