在Android应用程序

时间:2017-05-03 07:30:21

标签: android androidhttpclient

好的伙计们,我在过去的24年里尝试了很多关于如何做到这一点的代码示例,但我无法解决任何问题。

我只是想将JSON身体传递给URL。 使用cURL BASH中的Runtime.getRuntime().exec("curl....."); 工作正常,我甚至向我们试图

JSON

但是,即使这并没有通过http正文,事实上我已经成功发送Runtime.getRuntime().exec(str)请求JSON以及其他几种方式,但没有他们通过var myPopup = $ionicPopup.show({ template: '<input type = "text" ng-model = "data.model"><br> ' , title: 'Name' , scope: $scope , buttons: [ { text: 'Cancel' }, { text: '<b>Search</b>' , type: 'button-positive' , onTap: function (e) { $ionicLoading.show(); $http.get(HTTPService.getHttpText() + 'Persons/' + $scope.data.model).then(function (resp) { console.log('Success', resp); $ionicLoading.hide(); }, function (err) { $ionicLoading.hide(); console.error('ERR', err); // err.status will contain the status code }) } } ] }); 身体。

我将不胜感激。

2 个答案:

答案 0 :(得分:0)

您应该使用Retrofit。 有很多样本herehere's同样的问题

答案 1 :(得分:0)

如果你想编写自己的方法: 这是一个。

private JsonObject postJsonObject(JsonObject jsonObject) {
        JsonObject nullresult = new JsonObject();
        nullresult.addProperty("success",-1);
        try {
            String data = jsonObject.toString();
            URL object = new URL(url); \\MENTION YOUR URL HERE

            HttpURLConnection httpURLConnection = (HttpURLConnection) object.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setConnectTimeout(8000);
            httpURLConnection.setReadTimeout(8000);

            OutputStreamWriter wr = new OutputStreamWriter(httpURLConnection.getOutputStream());
            wr.write(data);
            wr.flush();

            StringBuilder sb = new StringBuilder();
            int HttpResult = httpURLConnection.getResponseCode();
            if (HttpResult == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                br.close();
            }
            JsonObject result = new JsonParser().parse(sb.toString()).getAsJsonObject();

            if(result !=null)
                return result;
            else
                return nullresult;
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedJsonException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return nullresult;
    }

您还可以使用Ion之类的库。 链接:https://github.com/koush/ion

很容易理解android的网络库。他们有一些例子可以帮助你。