与身体Http请求 [英] Http request with body

查看:164
本文介绍了与身体Http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建
POST请求的网址是 http://url.com/api/auth/
与HTTP-身体authparams = {登录:登录,密码:pasword}
如何创建呢?我尝试

i need to create POST request url is http://url.com/api/auth/ with HTTP-Body authparams={"login":"login","password":"pasword"} how can i create it? i try

 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();

        }

但我得到一个坏的结果。

but i get a bad result

推荐答案

我觉得你missunderstanding一块$ C $的c您已经发布。这只是的发送的POST请求到服务器,但目前不处理来自它的响应。要做到这一点,你可以用一块code像这样的:

I think you are missunderstanding the piece of code you've posted. This just sends a POST request to the server, but currently doesn't process the response from it. To do so, you might use a piece of code like this:

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());

这篇关于与身体Http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆