Я должен выполнить http post-запрос к веб-сервису для аутентификации пользователя с помощью имени пользователя и пароля. Специалист по веб-сервису предоставил мне следующую информацию для построения HTTP Post-запроса.
POST /login/dologin HTTP/1.1 Host: webservice.companyname.com Content-Type: application/x-www-form-urlencoded Content-Length: 48
Это то, что я делаю HttpPost postRequest = new HttpPost(urlString); Как мне сконструировать остальные параметры?
Переведено автоматически
Ответ 1
Вот пример, ранее найденный по адресу androidsnippets.com (сайт в настоящее время больше не поддерживается).
// Create a new HttpClient and Post Header HttpClienthttpclient=newDefaultHttpClient(); HttpPosthttppost=newHttpPost("http://www.yoursite.com/script.php");
try { // Add your data List<NameValuePair> nameValuePairs = newArrayList<NameValuePair>(2); nameValuePairs.add(newBasicNameValuePair("id", "12345")); nameValuePairs.add(newBasicNameValuePair("stringdata", "AndDev is Cool!")); httppost.setEntity(newUrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request HttpResponseresponse= httpclient.execute(httppost);
// Try this should be the length of you content. // it is not neccessary equal to 48. // content.getBytes().length is not neccessarily equal to content.length() if the String contains non ASCII characters. connection.setRequestProperty("Content-Length", content.getBytes().length);
// Write body OutputStreamoutput= connection.getOutputStream(); output.write(content.getBytes()); output.close();
Вам нужно будет перехватить исключение самостоятельно.
Ответ 4
Я бы предпочел рекомендовать вам использовать Volley для выполнения запросов GET, PUT, POST ....
Сначала добавьте зависимость в ваш файл gradle.
compile 'com.he5ed.lib:volley:android-cts-5.1_r4'
Теперь используйте этот фрагмент кода для выполнения запросов.