简体   繁体   中英

How to call java web service from android app?

I've made simple web service where you have to provide your name. It will return "Hello "+your_Name.

At Server Side

myWebService.java

package pkg;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;


@WebService(serviceName = "myWebService")
public class myWebService {


    @WebMethod(operationName = "hello")
    public String hello(@WebParam(name = "name") String txt) {
        return "Hello " + txt + " !";
    }
}

At Client Side

Index.jsp

<%@page import="java.io.Writer"%>
<%@page import="org.json.JSONObject"%>
<%@page import="org.json.JSONArray"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="application/json; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form action="#">
            <input type="text" name="t1">
            <input type="submit" value="CLICK"><br>
        </form>
    </body>
</html>
    <%-- start web service invocation --%><hr/>
    <%
    try {
    pkg.MyWebService_Service service = new pkg.MyWebService_Service();
    pkg.MyWebService port = service.getMyWebServicePort();
    java.lang.String name = request.getParameter("t1");
    java.lang.String result = port.hello(name);

        out.write(result);

    } catch (Exception ex) 
    {

    }
    %>
    <%-- end web service invocation --%><hr/>

Output on Browser

在此处输入图片说明

So Web Service works fine when I call it from Browser. But problem occurs when I try to call it from Android.

build.gradle(Module: app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.akshay.httpclientdemo"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation files('libs/httpclient-4.5.9.jar')
    implementation files('libs/httpcore-4.4.11.jar')
}

AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.akshay.httpclientdemo">

        <uses-permission android:name="android.permission.INTERNET"/>
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

**activity_main.xml**
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/t1"
        android:layout_width="293dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/t2"
        android:layout_width="289dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/t1" />

    <Button
        android:id="@+id/btn"
        android:layout_width="132dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/t2" />

    <ProgressBar
        android:id="@+id/pBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity
{

    Button btn;
    EditText t1,t2;
    ProgressBar pBar;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn=(Button)findViewById(R.id.btn);
        t1=(EditText)findViewById(R.id.t1);
        t2=(EditText)findViewById(R.id.t2);
        pBar=(ProgressBar)findViewById(R.id.pBar);

        pBar.setVisibility(View.GONE);

        btn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                pBar.setVisibility(View.VISIBLE);
                new ExecuteTask().execute();
            }
        });
    }


    class ExecuteTask extends AsyncTask<String, Integer, String>
    {
        StringBuffer result;

        @Override
        protected String doInBackground(String... params) {

            try
            {
                String url = "http://localhost:8080/WebClient/index.jsp?t1="+t1.getText().toString();

                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet(url);

                HttpResponse response = client.execute(request);

                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                String line = "";
                result = new StringBuffer();

                while ((line = rd.readLine()) != null)
                {
                    result.append(line);
                }

                t2.setText(result.toString());
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }

            return result.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            pBar.setVisibility(View.GONE);
            t2.setText(result.toString());
        }
    }
}

Output

在此处输入图片说明

After Clicking Button, I get

在此处输入图片说明

Error Log

07-18 14:13:06.423 1394-1422/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 9295997 , only wrote 9295920
07-18 14:13:06.442 8162-8185/com.example.akshay.httpclientdemo D/NetworkSecurityConfig: No Network Security Config specified, using platform default
07-18 14:13:06.452 8162-8185/com.example.akshay.httpclientdemo W/System.err: org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8080 refused
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:193)
        at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
        at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
07-18 14:13:06.453 8162-8185/com.example.akshay.httpclientdemo W/System.err:     at com.example.akshay.httpclientdemo.MainActivity$ExecuteTask.doInBackground(MainActivity.java:64)
        at com.example.akshay.httpclientdemo.MainActivity$ExecuteTask.doInBackground(MainActivity.java:50)
        at android.os.AsyncTask$2.call(AsyncTask.java:304)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
    Caused by: java.net.ConnectException: Connection refused
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
        at java.net.Socket.connect(Socket.java:586)
        at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
        ... 14 more

    --------- beginning of crash
07-18 14:13:06.454 8162-8185/com.example.akshay.httpclientdemo E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: com.example.akshay.httpclientdemo, PID: 8162
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:318)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.StringBuffer.toString()' on a null object reference
        at com.example.akshay.httpclientdemo.MainActivity$ExecuteTask.doInBackground(MainActivity.java:83)
        at com.example.akshay.httpclientdemo.MainActivity$ExecuteTask.doInBackground(MainActivity.java:50)
        at android.os.AsyncTask$2.call(AsyncTask.java:304)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
        at java.lang.Thread.run(Thread.java:761) 


    --------- beginning of system
07-18 14:13:06.455 1674-1829/system_process W/ActivityManager:   Force finishing activity com.example.akshay.httpclientdemo/.MainActivity
07-18 14:13:06.462 1674-1829/system_process W/ActivityManager:   Force finishing activity com.example.akshay.httpclientdemo/.MainActivity
    Duplicate finish request for ActivityRecord{fc02510 u0 com.example.akshay.httpclientdemo/.MainActivity t92 f}
07-18 14:13:06.496 1310-2049/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 2691072
07-18 14:13:06.522 1310-1310/? E/EGL_emulation: tid 1310: eglCreateSyncKHR(1901): error 0x3004 (EGL_BAD_ATTRIBUTE)
07-18 14:13:06.667 1674-1691/system_process W/art: Long monitor contention with owner Binder:1674_2 (1686) at void com.android.server.am.ActivityManagerService.activityPaused(android.os.IBinder)(ActivityManagerService.java:6879) waiters=2 in void com.android.server.am.ActivityManagerService$3.handleMessage(android.os.Message) for 181ms
07-18 14:13:06.676 1674-2111/system_process W/art: Long monitor contention with owner Binder:1674_2 (1686) at void com.android.server.am.ActivityManagerService.activityPaused(android.os.IBinder)(ActivityManagerService.java:6879) waiters=3 in int com.android.server.am.ActivityManagerService.bindService(android.app.IApplicationThread, android.os.IBinder, android.content.Intent, java.lang.String, android.app.IServiceConnection, int, java.lang.String, int) for 188ms
07-18 14:13:06.811 6822-6839/com.example.akshay.todolist D/EGL_emulation: eglMakeCurrent: 0x997be600: ver 2 0 (tinfo 0xa6bf67e0)
07-18 14:13:06.846 8162-8178/com.example.akshay.httpclientdemo D/EGL_emulation: eglMakeCurrent: 0xb1a4e6a0: ver 2 0 (tinfo 0xa6b86880)
07-18 14:13:06.853 8162-8178/com.example.akshay.httpclientdemo D/OpenGLRenderer: endAllActiveAnimators on 0x99878300 (RippleDrawable) with handle 0x9953e240
07-18 14:13:06.872 1674-1752/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
07-18 14:13:06.872 1674-1752/system_process D/OpenGLRenderer: Swap behavior 1
07-18 14:13:06.872 1674-1752/system_process W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
07-18 14:13:06.872 1674-1752/system_process D/OpenGLRenderer: Swap behavior 0
07-18 14:13:06.883 1674-1752/system_process D/EGL_emulation: eglCreateContext: 0x971032a0: maj 2 min 0 rcv 2
07-18 14:13:06.893 1674-1752/system_process D/EGL_emulation: eglMakeCurrent: 0x971032a0: ver 2 0 (tinfo 0x97d9b700)
07-18 14:13:06.902 1674-1752/system_process D/EGL_emulation: eglMakeCurrent: 0x971032a0: ver 2 0 (tinfo 0x97d9b700)
07-18 14:13:07.163 1394-1422/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 9331460 , only wrote 9331200
    Not supplying enough data to HAL, expected position 9331210 , only wrote 9331200
07-18 14:13:07.181 1394-1422/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 9332030 , only wrote 9331920
07-18 14:13:07.432 1674-4893/system_process I/WindowManager: Destroying surface Surface(name=com.example.akshay.httpclientdemo/com.example.akshay.httpclientdemo.MainActivity) called by com.android.server.wm.WindowStateAnimator.destroySurface:2016 com.android.server.wm.WindowStateAnimator.destroySurfaceLocked:882 com.android.server.wm.WindowState.removeLocked:1456 com.android.server.wm.WindowManagerService.removeWindowInnerLocked:2484 com.android.server.wm.WindowManagerService.removeWindowLocked:2442 com.android.server.wm.WindowManagerService.removeWindowLocked:2311 com.android.server.wm.WindowManagerService.removeWindow:2306 com.android.server.wm.Session.remove:202 
07-18 14:13:09.582 1394-1423/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 9561758 , only wrote 9447120
07-18 14:13:23.586 1674-1758/system_process D/WifiNative-HAL: Failing getSupportedFeatureset because HAL isn't started
07-18 14:13:23.587 1674-1695/system_process E/BluetoothAdapter: Bluetooth binder is null
07-18 14:13:23.588 1674-1695/system_process E/BatteryStatsService: no controller energy info supplied
07-18 14:13:23.592 1674-1695/system_process E/KernelCpuSpeedReader: Failed to read cpu-freq: /sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state (No such file or directory)
07-18 14:13:23.592 1674-1695/system_process E/KernelUidCpuTimeReader: Failed to read uid_cputime: /proc/uid_cputime/show_uid_stat (No such file or directory)
07-18 14:13:23.593 1674-1695/system_process E/BatteryStatsService: modem info is invalid: ModemActivityInfo{ mTimestamp=0 mSleepTimeMs=0 mIdleTimeMs=0 mTxTimeMs[]=[0, 0, 0, 0, 0] mRxTimeMs=0 mEnergyUsed=0}
07-18 14:14:00.138 1674-1674/system_process I/EntropyMixer: Writing entropy...
07-18 14:14:17.212 1674-1692/system_process I/ProcessStatsService: Prepared write state in 39ms

You're trying to connect to localhost. Localhost is the machine the code is running on. But your server isn't on your phone (even if using an emulator, the emulator is a VM- it counts as a separate machine). So its not connecting, and not getting any data. Use the real url/ip address.

You also need to account for the case of a connection not working for some reason (for example, the server is down) and try to handle it more gracefully than a crash. Your problem here is that you depend on result being non-null in the return of doInBackground. You can fix this by moving return result.toString into the try block, and putting return null where you have it now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM