繁体   English   中英

带有正文的Http请求

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM