简体   繁体   中英

Http request with body

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

You need to convert your post data into Json format (you can use google library gson or by using org.json).

And then add your json string to the post data nameValuePair.add(new BasicNameValuePair("login", "A@asd.ru"))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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