从 Android 我想用 POST 方法调用 API [英] From Android I want to call API with POST method

查看:52
本文介绍了从 Android 我想用 POST 方法调用 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从 Postman 提交请求时收到 API 的响应,如图所示

I am getting response from API when I submit request from Postman like shown in the image

screenshot1.jpg = 我需要传递的数据screenshot2.jpg = 我们得到的结果

screenshot1.jpg = The data I need to pass screenshot2.jpg = The result we get

我尝试使用以下代码通过 android 调用它们,但它不起作用,

I tried calling them through android with below code but it's not working,

JSONObject login = new JSONObject();
login.put("username", userName);
login.put("password", password);
login.put("platform", "ANDROID");
login.put("location", "56.1603092,10.2177147");

String str = WebServices.excutePost(url, login);


public static String excutePost(String targetURL, JSONObject urlParameters) {
    URL url;
    HttpURLConnection connection = null;
    try {


        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/raw");

        connection.setRequestProperty("Content-Length", "" +
                Integer.toString(urlParameters.toString().getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");


        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);


        //Send request

        OutputStream out = new BufferedOutputStream(connection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.write(String.valueOf(urlParameters.toString().getBytes("UTF-8")));
        out.close();
        //connection.disconnect();

        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();

    } catch (Exception e) {

        e.printStackTrace();
        return null;

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
}

推荐答案

您可以使用以下方法:

public String executePost(String targetURL,String urlParameters) {
    int timeout=5000;
    URL url;
    HttpURLConnection connection = null;
    try {
        // Create connection

        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/json");

        connection.setRequestProperty("Content-Length",
                "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);

        // Send request
        DataOutputStream wr = new DataOutputStream(
                connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        // Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();

    } catch (SocketTimeoutException ex) {
        ex.printStackTrace();

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException ex) {

        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

您可以创建 URL 参数,例如:

You can create URL parameters like:

JSONObject loginParams = new JSONObject();
loginParams .put("username", userName);
loginParams .put("password", password);
loginParams .put("platform", "ANDROID");
loginParams .put("location", "56.1603092,10.2177147");

调用方法如:

executePost(serviceURL,loginParams.toString());

这篇关于从 Android 我想用 POST 方法调用 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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