[英]Http request with body
我需要使用HTTP正文authparams = {“ login”:“ login”,“ password”:“ pasword”}創建POST請求url為http://url.com/api/auth/ ,如何創建它? 我嘗試
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost("http://url.com/api/auth/");
// Building post parameters, key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("login", "A@asd.ru"));
nameValuePair.add(new BasicNameValuePair("password", "123"));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("myLogs:", response.toString());
HttpEntity entity = response.getEntity();
Log.d("myLogs:",EntityUtils.toString(entity) );
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
但我得到一個不好的結果
您需要將帖子數據轉換為Json格式(可以使用Google庫gson或使用org.json)。
然后將您的json字符串添加到發布數據nameValuePair.add(new BasicNameValuePair("login", "A@asd.ru"))
我認為您誤解了您發布的那段代碼。 這只是向服務器發送 POST請求,但當前不處理來自服務器的響應。 為此,您可以使用如下代碼:
InputStream ips;
ips = response.getEntity().getContent();
final BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while (true) {
s = buf.readLine();
if ((s == null) || (s.length() == 0))
break;
sb.append(s);
}
buf.close();
ips.close();
Log.i("Response", "My response is: " + sb.toString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.