Android AsyncHttpClient向服务器发送HTTP POST请求
我正在尝试向服务器发送HTTP POST请求。 我的服务器接受这样的卷曲:Android AsyncHttpClient向服务器发送HTTP POST请求,android,Android,我正在尝试向服务器发送HTTP POST请求。 我的服务器接受这样的卷曲: curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d "{\"City\":\"Lodz\", \"FirstName\":\"Patryk\"}" http://127.0.0.1:8000/addemployees AsyncHttpClient httpClient = new AsyncHttp
curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d "{\"City\":\"Lodz\", \"FirstName\":\"Patryk\"}" http://127.0.0.1:8000/addemployees
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.addHeader("Accept", "application/json");
RequestParams jsonParams = new RequestParams();
jsonParams.put("City", city);
jsonParams.put("FirstName", city);
Log.i("requestParams: ", jsonParams.toString());
httpClient.post("http://myComputerIP:8000/addemployees", jsonParams, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject obj) {
String jsonResponse = obj.toString();
Log.i("TAG", "onSuccess: " + jsonResponse);
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.e("TAG", "onFailure: " + errorResponse);
}
我还尝试使用Android发送HTTP POST请求。
我的代码如下所示:
curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d "{\"City\":\"Lodz\", \"FirstName\":\"Patryk\"}" http://127.0.0.1:8000/addemployees
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.addHeader("Accept", "application/json");
RequestParams jsonParams = new RequestParams();
jsonParams.put("City", city);
jsonParams.put("FirstName", city);
Log.i("requestParams: ", jsonParams.toString());
httpClient.post("http://myComputerIP:8000/addemployees", jsonParams, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject obj) {
String jsonResponse = obj.toString();
Log.i("TAG", "onSuccess: " + jsonResponse);
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.e("TAG", "onFailure: " + errorResponse);
}
但是,我的Android代码中出现了一些错误,因为我遇到了以下错误:
TAG: onFailure: {"message":"Internal Server Error"}
我试过几种解决办法,但都不管用。我应该如何改变它?谢谢您应该以JSON格式发送数据。为此,您需要向
POST
方法传递一个StringEntity
对象,该对象包含已格式化的JSON字符串,而不是RequestParams
JSONObject json = new JSONObject();
json.put("City", city);
json.put("FirstName", city);
StringEntity entity = new StringEntity(json.toString());
您应该以JSON格式发送数据。为此,您需要向
POST
方法传递一个StringEntity
对象,该对象包含已格式化的JSON字符串,而不是RequestParams
JSONObject json = new JSONObject();
json.put("City", city);
json.put("FirstName", city);
StringEntity entity = new StringEntity(json.toString());