HttpPost需要超过3秒才能得到结果

时间:2014-05-15 12:40:14

标签: java android json apache http

我面临一个非常糟糕/丑陋的问题。我的Android应用程序需要发送/接收JSON字符串,问题是需要3到9秒才能收到答案。如果我使用邮差Chrome扩展程序,服务器响应非常快。这是代码:

public class JSONHandler{
    private HttpClient client;
    private HttpPost post;

    public JSONHandler(){
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        client = new DefaultHttpClient(params);
        post = new HttpPost("http://secretserver.net/index.php");
        post.setHeader("Content-type", "application/json");
    }

    private JSONObject sendJSON(JSONObject obj){
        StringEntity se = null;
        try {
            se = new StringEntity(obj.toString());
            Log.d("JSON Angekommen",se.toString());
        } catch (UnsupportedEncodingException e) {
            Log.e("Encoding", "Exception while encoding");
        }
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);
        try {
            HttpResponse response = client.execute(post);
            //TODO: Timeout Handling
            String json_string = EntityUtils.toString(response.getEntity());
            return new JSONObject(json_string); 

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}

在本代码中,我正在异步任务中执行方法:

public class Updater extends AsyncTask<Activity,String,String>{

        private boolean connected;
        private Activity main;

        @Override
        protected void onPreExecute() {
            ConnectionHandler conn = new ConnectionHandler(context);
            connected = conn.isConnected();
        }

        @Override
        protected String doInBackground(Activity... acs) {
            main = acs[0];
            String json_String;
            if(connected){
                JSONHandler json = new JSONHandler();
                json_String = json.sendRegister("Peter", "peter@gmx.de", "Feld 2", "Happy", "Developer").toString();
                return json_String;
            }else{
                return "Not Working!";
            }
        }

        @Override
        protected void onPostExecute(String result){
            Notificator.doNotifyNoClickable(main, "PHP Antwort", result);

            Log.d("JSON", result);
        }
    }

0 个答案:

没有答案