从Android我想用POST方法调用API

时间:2016-01-27 06:37:32

标签: android api post

当我从邮递员提交请求时,我会收到来自API的回复,如图所示

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

screenshot1.jpg screenshot2.jpg

我尝试用下面的代码通过android调用它们,但它没有用,

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

3 个答案:

答案 0 :(得分:3)

您可以使用以下方法:

    Route::get('goclozer/country','GoClozerController@getCountry');

您可以创建以下网址参数:

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;
}

调用方法如:

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

答案 1 :(得分:0)

您可以使用retrofit库更轻松地与REST服务实现网络通信。

顺便说一句,您可以尝试我的问题解决方案:

  • 首先,创建一个executeHttp方法

            private JSONObject executeHttp(HttpUriRequest request, Context context) throws ClientProtocolException, IOException {
            HttpParams httpParameters = new BasicHttpParams();
                // Set the timeout in milliseconds until a connection is established.
                // The default value is zero, that means the timeout is not used.
                int timeoutConnection = 3000;
                HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                // Set the default socket timeout (SO_TIMEOUT)
                // in milliseconds which is the timeout for waiting for data.
                int timeoutSocket = 10000;
                HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    
                DefaultHttpClient client = new DefaultHttpClient(httpParameters);
                // add your header in here - I saw your header has 7 params
                request.addHeader("Authorization", getToken());
                request.addHeader("APIKey", API_KEY);
                request.addHeader("Content-Type", "application/x-www-form-urlencoded");
                request.addHeader("X-Request-Mime-Type", "application/json;");
                HttpResponse execute = client.execute(request);
                InputStream content = execute.getEntity().getContent();
                // implement your handle response here, below is just an example
                try {
                     return new JSONObject().put("content", this.convertStreamToByteArray(content));
                } catch (JSONException e) {
                //Crashlytics.logException(e);
                     Log.e(LOG_TAG, "Error converting stream to byte array: " + e.getMessage());
                     return new JSONObject();
    
                }
            }
    

然后创建一个处理POST请求的方法

public JSONObject doPost(List<NameValuePair> headerParams, List<NameValuePair> parameters, String url, Context context) throws ClientProtocolException, IOException {
        HttpPost httpPost = new HttpPost(url);
        // add the header if needed
        if (headerParams != null) {
            for (NameValuePair headerParam: headerParams) {
                httpPost.addHeader(headerParam.getName(), headerParam.getValue());
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));

        return executeHttp(httpPost, context);
    }

最后,调用刚创建的api。

JSONObject json = doPost(header, nameValuePairs, yourUrl, context);
带有nameValuePairs的

创建
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("username", userName));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            nameValuePairs.add(new BasicNameValuePair("platform", "ANDROID"));
            nameValuePairs.add(new BasicNameValuePair("location", "56.1603092,10.2177147"));

答案 2 :(得分:0)

问题是使用stringbuffer类,我使用字符串来获得响应,它工作得很好。感谢大家的意见和答案。