我需要创造 POST请求网址为http://url.com/api/auth/ 使用HTTP-Body authparams = {“login”:“login”,“password”:“pasword”} 我怎么能创造它?我试试
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();
}
但是我得到了一个糟糕的结果
答案 0 :(得分:0)
您需要将帖子数据转换为Json格式(您可以使用google library gson或使用org.json)。
然后将您的json字符串添加到帖子数据中
nameValuePair.add(new BasicNameValuePair("login", "A@asd.ru"))
答案 1 :(得分:0)
我认为您错过了您发布的代码段。这只是向服务器发送 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());