0

以下で説明するように、Android で Web サービスを呼び出すメソッドがあります。

クラスがこのメソッドを呼び出すと、例外は表示されず、System.out.println("entered into call service method 2");ログまでしか表示されません。logcat の状態response = httpclient.execute(httppost);が機能しSystem.out.println("entered into call service method 3");ておらず、logcat にも例外が表示されていないことがわかります。なぜそう思うのですか?修正方法は?

           public void callService() throws Exception {
        System.out.println("entered into call service method");
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://localhost:81/a.php");
        HttpResponse response;
        System.out.println("entered into call service method 1");
        try{
            System.out.println("entered into call service method 2");
            **response = httpclient.execute(httppost);**
            System.out.println("entered into call service method 3");
4

1 に答える 1

1

この関数を別の Thread / AsyncTask で呼び出しますか? アプリでリクエストが頻繁に使用される場合は、Service の使用を検討することもお勧めします。

これは私にとってはうまくいく POST メソッドですが、何らかの形で非同期に呼び出すことを忘れないでください。

public void executePost(String url, List<NameValuePair> postParams) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    InputStream is = null;
    try {
        httppost.setEntity(new UrlEncodedFormEntity(postParams));
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int inChar;
                while ((inChar = is.read()) != -1) {
                    bos.write(inChar);
                }

                String resp = bos.toString();
                // report back the resp e.g. via LocalBroadcast message 
            } else {
                // report back e.g. via LocalBroadcast message 
            }
        }
        else {
            // report back e.g. via LocalBroadcast message 
        }
    } catch (Exception e) {
            // report back the exception e.g. via LocalBroadcast message 
        // exception message: e.getMessage()
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
于 2013-01-02T08:25:39.523 に答える