android BaseJsonHttpResponseHandler给我response = null

时间:2015-11-26 12:14:55

标签: android httphandler

我遇到了这个问题,基本上我可以从服务器收到标题,但响应为空,我不明白为什么? 我看到服务器日志,一切正常,我尝试了curl请求,即使一切正常,但在我的应用程序中,我无法收到回复。

try {
                final String token2 = mPreferences.getString("auth_token", "");

                // open a URL connection to the Servlet
                final URL url = new URL(upLoadServerUri);

                final RequestParams params = new RequestParams();

                //create the hashmap with the parameters for Strings
                HashMap<String, String> paramMap = new HashMap<String, String>();
                paramMap.put("spot[title]", mtitle);
                paramMap.put("spot[address]", maddress);
                paramMap.put("spot[country]", mcountry);
                paramMap.put("spot[shot_level]", "easy");
                paramMap.put("spot[photos_attributes][0][description]", mdescription);

                params.put("spot[latitude]", googlelat);
                params.put("spot[longitude]", googlelng);
                params.put("", paramMap);
                //params.put("", paramMapInt);

                File myFile = new File(sglimagepath);
                try {
                    params.put("spot[photos_attributes][0][ref]", sourceFile);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                AsyncHttpClient client2 = new SyncHttpClient();
AsyncHttpClient client2 = new SyncHttpClient();
//check if needs this header or I can take off this and leave just the url+token2
            client2.addHeader("x-auth-token", token2);

            client2.post(String.valueOf(url), params, new BaseJsonHttpResponseHandler(String.valueOf(Looper.getMainLooper())) {

                /**
                 * Base abstract method, handling defined generic type
                 *
                 * @param statusCode      HTTP status line
                 * @param headers         response headers
                 * @param rawJsonResponse string of response, can be null
                 * @param response        response returned by {@link #parseResponse(String, boolean)}
                 */
                @Override
                public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, String rawJsonResponse, Object response) {

                    onPostExecute((JSONObject)response);

                }

                /**
                 * Base abstract method, handling defined generic type
                 *
                 * @param statusCode    HTTP status line
                 * @param headers       response headers
                 * @param throwable     error thrown while processing request
                 * @param rawJsonData   raw string data returned if any
                 * @param errorResponse response returned by {@link #parseResponse(String, boolean)}
                 */
                @Override
                public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) {

                }

                /**
                 * Should return deserialized instance of generic type, may return object for more vague
                 * handling
                 *
                 * @param rawJsonData response string, may be null
                 * @param isFailure   indicating if this method is called from onFailure or not
                 * @return object of generic type or possibly null if you choose so
                 * @throws Throwable allows you to throw anything from within deserializing JSON response
                 */
                @Override
                protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                    return null;
                }

我执行此请求是因为我向服务器发送图像,服务器response_code为201表示一切正常,因此响应将包括&#34; user_id&#34;然后在收到user_id后我可以再发一次请求。谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

试试这种方式

            final RequestParams params = new RequestParams();

            //create the hashmap with the parameters for Strings
            params.add("spot[title]", mtitle);
            params.add("spot[address]", maddress);
            params.add("spot[country]", mcountry);
            params.add("spot[shot_level]", "easy");
            params.add("spot[photos_attributes][0][description]", mdescription);

            params.add("spot[latitude]", googlelat);
            params.add("spot[longitude]", googlelng);


            try {
        params.put("spot[photos_attributes][0][ref]", new File(sglimagepath));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

并观察日志以查看文件是否已找到

编辑     这是我的代码,它的工作正常

final RequestParams requestParams = new RequestParams();
        requestParams.add("Event[user_id]", user_id);
        requestParams.add("Event[city]", city);
        requestParams.add("Event[title]", title);
        requestParams.add("Event[short_description]", shortDesc);
        requestParams.add("Event[description]", Desc);
        requestParams.add("Event[latitude]", lat);
        requestParams.add("Event[longitude]", longi);
        requestParams.add("Event[type_id]", type_id);
        try {
            Log.d("imgPath", "img path = " + img);
            File file = new File(img);
            requestParams.put("Event[img]" , file);
            requestParams.add("Event[img]" , imgName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        requestParams.setContentEncoding("utf-8");

        String url = ServerConnection.ipAdresss + ServerConnection.createEvents;

        AsyncHttpClient client = new AsyncHttpClient();
//        client.addHeader("Content-Type","multipart/form-data");
        client.post(url, requestParams, new TextHttpResponseHandler() {


            @Override
            public void onPostProcessResponse(ResponseHandlerInterface instance, cz.msebera.android.httpclient.HttpResponse response) {
                super.onPostProcessResponse(instance, response);
            }

            @Override
            public void sendResponseMessage(HttpResponse response) throws IOException {
                super.sendResponseMessage(response);
                Log.d("Failed", "failed " + response.getEntity().toString());


            }



            @Override
            public void onStart() {
                // called before request is started
                progressDialog.show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("Failed", "failed " + throwable.getMessage());
                SUtility.makeToast(context, "Error = " + throwable.getMessage());
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("Success", "success " + responseString);
                try {
                    ParseResp(responseString);

                } catch (Exception e) {
                    e.printStackTrace();
                    SUtility.makeToast(context, "Error retrieving Data");
                }

            }


            @Override
            public void onFinish() {
                super.onFinish();
                Log.d("Success", "finish");
                if (progressDialog.isShowing())
                    progressDialog.dismiss();


            }

            @Override
            public void onRetry(int retryNo) {
                // called when request is retried
            }
        });
    }