Использование HttpClient и HttpPost в Android с параметрами публикации
Я пишу код для приложения Android, которое должно принимать данные, упаковывать их как Json и публиковать на веб-сервере, который, в свою очередь, должен отвечать с помощью json.
Использование запроса GET работает нормально, но по какой-то причине при использовании POST все данные, похоже, удаляются, а сервер ничего не получает.
Вот фрагмент кода:
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
BasicCookieStore cookieStore = new BasicCookieStore();
httpClient.setCookieStore(cookieStore);
String uri = JSON_ADDRESS;
String result = "";
String username = "user";
String apikey = "something";
String contentType = "application/json";
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
} catch (JSONException e) {
Log.e(TAG, "JSONException: " + e);
}
HttpPost httpPost = new HttpPost(uri);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonObj.toString()));
HttpGet httpGet = null;
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", contentType);
httpPost.setHeader("Accept", contentType);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "UnsupportedEncodingException: " + e);
}
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
InputStream is = httpEntity.getContent();
result = StringUtils.convertStreamToString(is);
Log.i(TAG, "Result: " + result);
}
} catch (ClientProtocolException e) {
Log.e(TAG, "ClientProtocolException: " + e);
} catch (IOException e) {
Log.e(TAG, "IOException: " + e);
}
return result;
Я думаю, что следовал общим рекомендациям о том, как создавать параметры и публиковать их, но, видимо, нет.
Любая помощь или указатели, где я могу найти решение, очень приветствуются в этот момент (потратив несколько часов, осознавая, что никакие почтовые данные никогда не отправлялись). Настоящий сервер работает под управлением Wicket на Tomcat, но я также протестировал его на простой странице PHP, без разницы.
4 ответа
Вы пытались сделать это без объекта JSON и только что передали две пары Basicnamevalue? Кроме того, это может иметь какое-то отношение к вашим настройкам сервера
Обновление: это фрагмент кода, который я использую:
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(connection);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("HTTP", "HTTP: OK");
} catch (Exception e) {
Log.e("HTTP", "Error in http connection " + e.toString());
}
На самом деле вы можете отправить его как JSON следующим образом:
// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
Открытый класс GetUsers расширяет AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String connect()
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost htopost = new HttpPost("URL");
htopost.setHeader(new BasicHeader("Authorization","Basic Og=="));
try {
JSONObject param = new JSONObject();
param.put("PageSize",100);
param.put("Userid",userId);
param.put("CurrentPage",1);
htopost.setEntity(new StringEntity(param.toString()));
// Execute the request
HttpResponse response;
response = httpclient.execute(htopost);
// Examine the response status
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// A Simple JSONObject Creation
json = new JSONArray(result);
// Closing the input stream will trigger connection release
instream.close();
return ""+response.getStatusLine().getStatusCode();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected String doInBackground(String... urls) {
return connect();
}
@Override
protected void onPostExecute(String status){
try {
if(status.equals("200"))
{
Global.defaultMoemntLsit.clear();
for (int i = 0; i < json.length(); i++) {
JSONObject ojb = json.getJSONObject(i);
UserMomentModel u = new UserMomentModel();
u.setId(ojb.getString("Name"));
u.setUserId(ojb.getString("ID"));
Global.defaultMoemntLsit.add(u);
}
userAdapter = new UserAdapter(getActivity(), Global.defaultMoemntLsit);
recycleView.setAdapter(userMomentAdapter);
recycleView.setLayoutManager(mLayoutManager);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Я только что проверил, и у меня такой же код, как у вас, и он работает безупречно. Разница лишь в том, как я заполняю свой список для параметров:
Я использую: ArrayList<BasicNameValuePair> params
и заполните это так:
params.add(new BasicNameValuePair("apikey", apikey);
Я не использую JSONObject для отправки параметров на веб-сервисы.
Вы обязаны использовать JSONObject?