3

我正在开发一个需要在其中使用 Web 服务的应用程序。因为我得到了 php 文件和 json 数据,被要求做 web 服务。由于我是开发新手,所以我不知道如何在 android native 中进行 web 服务编码。经过长时间的搜索,我知道通过使用 SOAP 和 REST,我们可以在 android 中使用 Web 服务。

任何人都可以向我推荐任何材料以及如何在 android native 中使用 JSON webservices。我们是否需要使用 SOAP 和 REST 服务在 android 中实现 Json Webservices,或者有任何其他可能在不使用 SOAP 和 REST 服务的情况下获取代码。

由于我是新来开发任何小的帮助将不胜感激。

4

4 回答 4

2

在我看来,最简单的方法是使用HttpClient发出请求。

然后用一些库解析结果,例如GSON

如果您还必须以 JSON 格式发送参数,您可以使用POSTwithHttpClient发送 JSON 字符串。

编辑:示例可能如下所示:

public class DataObject {
    private Integer intField;
    private String strField;
    // This is a class which object will be sent through http
}

public class Client {
    public DataObject getData() {
        URL url = new URL("http://www.android.com/");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        try {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            //Here you have to read data from InputStream to String
            String jsonData = readStream(in);
            //Here you parse String using GSON
            return (new Gson()).fromJson(jsonData,DataObject.class);
        finally {
            urlConnection.disconnect();
        }
    }
}
于 2012-09-06T07:41:47.373 回答
1

对于 JSON

    public class HttpRequests {
    private  InputStream is = null;
    public HttpRequests() { }
    public  String[] makeHttpRequest(String url, String method,List<NameValuePair> params) {
    String[] result = new String[2];
    try {
         if(method == "POST"){
             DefaultHttpClient httpClient = new DefaultHttpClient();
             HttpPost httpPost = new HttpPost(url);
             httpPost.setEntity(new UrlEncodedFormEntity(params));
             HttpResponse httpResponse = httpClient.execute(httpPost);
             HttpEntity httpEntity = httpResponse.getEntity();
             is = httpEntity.getContent();
             result[0]="true";
         }else if(method == "GET"){
             DefaultHttpClient httpClient = new DefaultHttpClient();
             String paramString = URLEncodedUtils.format(params, "utf-8");
             url += "?" + paramString;
             HttpGet httpGet = new HttpGet(url);
             HttpResponse httpResponse = httpClient.execute(httpGet);
             HttpEntity httpEntity = httpResponse.getEntity();
             is = httpEntity.getContent();
             result[0]="true";
         }          
    }catch (UnsupportedEncodingException e) {
        result[0]=e.toString();
    }catch (ClientProtocolException e) {
        result[0]=e.toString();
    }catch (IOException e) {
        result[0]=e.toString();
    }
    if(result[0]=="true"){
        try {
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
             StringBuilder sb = new StringBuilder();
             String line = null;
             while ((line = reader.readLine()) != null) 
             {
               sb.append(line + "\n");
             }
             is.close();
             result[1]= sb.toString();
             return result;
        }catch (Exception e) {
            result[0]= e.toString();
            return result;
        }
    }else 
         return result;
}

其中 List 是数组,其中包含您要像这样发送的项目

      List<NameValuePair> params = new ArrayList<NameValuePair>();
         params.add(new BasicNameValuePair("Name",name1));
         params.add(new BasicNameValuePair("Email",email1));



              HttpRequests myHttpRequests=new HttpRequests();
         String[] responce= myHttpRequests.makeHttpRequest(SignUpURL,
                "POST", params); 
于 2012-09-06T07:50:28.607 回答
1

对于应用程序和服务器之间的连接,您需要创建 api 类,

public class PostParseGet {

public Context mActivity;
public boolean isNetError = false;
public boolean isConnectionTimeError = false;
public boolean isOtherError = false;
public boolean isDataError = false;
Object mFillObject;
//    List<PropertyInfo> mPropertyInfo;
//
//  CommonHelper mCommonHelper;
//
//    SoapObject mSoapObjectRequest;

HashMap<String, String> mHashMap;

Gson mGson;

public PostParseGet(Context context) {
    mActivity = context;
    mGson = new Gson();
    //      mCommonHelper= new CommonHelper(mActivity);
}

public boolean check_Internet(Context mContext){
    ConnectivityManager mConnectivityManager;
    NetworkInfo mNetworkInfo;
    mConnectivityManager= (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

    if(mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
        return true;
    else
        return false;
}

public static boolean isInternetOncheck(Context context) {
    ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (!(connec.getActiveNetworkInfo() != null && connec.getActiveNetworkInfo().isAvailable() && connec.getActiveNetworkInfo().isConnected())) {
        //            AppLog.logString(TAG+"Internet not avialable");
        return false;
    } else {
        //            AppLog.logString(TAG+"Internet available");
        return true;
    }
}

public Object httpPostData(String method,Object mObject,List<NameValuePair> postParameters,String json,String AddArrayName){
    BufferedReader in = null;

    isOtherError = false;
    isConnectionTimeError = false;

    mFillObject= null;

    if(check_Internet(mActivity)){
        isNetError = false;
        isDataError=false;
        try {
            mFillObject = mObject.getClass().newInstance();

            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            int timeoutConnection = 30*1000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT) 
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 30*1000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            HttpClient client = new DefaultHttpClient(httpParameters);
            //                String url = TagValues.SCU_URL+method;
            String url = method;
            HttpPost request = new HttpPost(url);
            System.out.println("-----url "+url);
            if(json!=null && !json.equalsIgnoreCase("")){ 
                StringEntity params =new StringEntity(json.toString(), "UTF-8");
                params.setContentType("application/json");
                request.setEntity(params);
                System.out.println("-----parameters "+json);
            }else{
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
                request.setEntity(formEntity);
                System.out.println("-----parameters "+postParameters.toString());
            }
            HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            //                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            String result="";

            try {
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                result = sb.toString();

            }catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    in.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }


            if(result!=null)

                if(!AddArrayName.equalsIgnoreCase("")){
                    result = "{"+AddArrayName+":"+result+"}";

                }
            //                    Log.i("Appname", "Response: \n" + result);
            System.out.println("------- Final data: "+result);

            mFillObject = mGson.fromJson(result, mFillObject.getClass());

        }catch (Exception e) {
            e.printStackTrace();
            isOtherError = true;
        }
    }else{
        isNetError = true;            
    }
    return mFillObject;
}
}

创建解析器类后,您需要为后台进程创建异步任务,以便从 Web 服务器推送和获取数据,如下所示,

public class ThreadAsyncTask extends AsyncTask<String, Void, Object> {
private String TAG = "Async: ";
private Dialog mAlert_Dialog;
private String method;
private Context con;
private String json;
private Object mObject;
private OnTaskCompleted listener;
private PostParseGet mPostParseGet;
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
private String AddArrayname;

public interface OnTaskCompleted{
    void onTaskCompleted(String method, Object result);
}

public ThreadAsyncTask(){

}

/**
 * 
 * @param listener
 * @param con
 * @param json
 * @param method
 */
public ThreadAsyncTask(OnTaskCompleted listener,Context con,Object object, String json, String method,List<NameValuePair> postParameters,String AddArrayName) {
    // TODO Auto-generated constructor stub
    this.listener = listener;
    this.con = con;
    this.json = json;
    this.method = method;
    this.mObject = object;
    this.postParameters = postParameters;
    this.AddArrayname = AddArrayName;
}

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    mAlert_Dialog = new Dialog(con);
    mAlert_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mAlert_Dialog.setContentView(R.layout.dailog_progressbar);
    mAlert_Dialog.setCancelable(false);
    mAlert_Dialog.show();
}

@Override
protected Object doInBackground(String... urls) {
//        Parcelable mParcelable;
    for (String url : urls) {
        if (isCancelled()) {
            break;
        }

        mPostParseGet = new PostParseGet(con);
        mObject = mPostParseGet.httpPostData(method,mObject,postParameters,json,AddArrayname);

//            Utility ul=new Utility();
//            result = (ul.setDataFromWebServiceSOAP(con,method, json));
    }
    return mObject;
}

@Override
protected void onPostExecute(Object result) {
    mAlert_Dialog.dismiss();
    if (listener != null)
        listener.onTaskCompleted(method,result);
}
}

最后你需要在你的活动类中定义并启动网络服务......

mTextViewLogin.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//                        postParameters.add(new     BasicNameValuePair("username",mEditTextUsername.getText().toString()));
//                        postParameters.add(new     BasicNameValuePair("password",mEditTextPassword.getText().toString()));

                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("username", mEditTextUsername.getText().toString());
                        jsonObject.put("password", mEditTextPassword.getText().toString());
                    }catch (JSONException e1) {
                        e1.printStackTrace();
                    }

                    if(PostParseGet.isInternetOncheck(LoginActivity.this)){
                        GetCommentList(TagValues.LOGIN_URL,jsonObject.toString(),postParameters);
                    }else{
                        CustomeDialog.dispDialog(LoginActivity.this, "Internet not available");
                    }

}
        });
public void GetCommentList(String methodName,String json,List<NameValuePair> postParameters){
    try {

        mParcelableClass= new ParcelableClass();
        ThreadAsyncTask testImple=new ThreadAsyncTask(listener, LoginActivity.this,mParcelableClass,json,methodName,postParameters,"");
        testImple.execute("");

    }catch (NullPointerException e) {}
}

private OnTaskCompleted listener = new OnTaskCompleted(){
    @Override
    public void onTaskCompleted(String methodName,Object result){

        if(result!=null){

            mParcelableClass= (ParcelableClass)result;
            if(mParcelableClass!=null && mParcelableClass.getStatus()!=null && mParcelableClass.getStatus().equalsIgnoreCase("success")){
                try {

                    Intent mIntent = new Intent(LoginActivity.this,YourSecondActivity.class);
                    startActivity(mIntent);
                    overridePendingTransition(R.anim.right_left, R.anim.right_left2);

                }catch (NullPointerException e){
                    e.printStackTrace();
                    dispDialog(LoginActivity.this, "Invalid responce\n"+ e.toString());
                    return;
                }catch (Exception e) {
                    e.printStackTrace();
                    dispDialog(LoginActivity.this, "Invalid responce\n"+ e.toString());
                    return;
                }
            }else{
                dispDialog(LoginActivity.this, "Invalid Credential");
            }
        }
    }

};

进度对话框 xml 看起来像

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/backrepeat"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="@dimen/margin_5"
    android:gravity="center"
    android:orientation="horizontal"
    android:padding="@dimen/margin_10" >

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:indeterminate="true" />

    <TextView
        android:id="@+id/txtMessage_progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/margin_10"
        android:gravity="center"
        android:padding="@dimen/margin_10"
        android:text="Please wait..."
        android:textColor="@color/textColor"
        android:textSize="@dimen/textsize_10sp"
        android:textStyle="bold" />
</LinearLayout>

警报对话框创建者

    public static void dispDialog(Activity ac,String dialogMsg){
    final Activity activity=ac;
    final Dialog Alert_Dialog = new Dialog(ac);
    Alert_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    Alert_Dialog.setContentView(R.layout.dailog_error);
    ((TextView)Alert_Dialog.findViewById(R.id.txtMessage)).setText(""+dialogMsg);

    Alert_Dialog.setCancelable(false);
    Alert_Dialog.show();
    ((Button) Alert_Dialog.findViewById(R.id.ok)).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Alert_Dialog.cancel();
            activity.finish();
            activity.overridePendingTransition(R.anim.left_right, R.anim.left_right2);
        }
    });

parcelabel 类也定义为

public class ParcelabelClass implements Parcelable{

private List<GradeDataList> GradeList;

public List<GradeDataList> getGradeList() {
    return GradeList;
}

public void setGradeList(List<GradeDataList> listData) {
    GradeList = listData;
}

public GradeList(){
    GradeList = new ArrayList<GradeDataList>();
    //        AutoCompleteIdName = new ArrayList<VoucherDataList>();
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel arg0, int arg1) {
    arg0.writeTypedList(GradeList);
    //        arg0.writeTypedList(AutoCompleteIdName);

}

public static Parcelable.Creator<GradeList> CREATOR= new Creator<GradeList>() {

    @Override
    public GradeList[] newArray(final int size) {
        return new GradeList[size];
    }

    @Override
    public GradeList createFromParcel(final Parcel source) {
        return new GradeList(source);
    }
};

public GradeList(final Parcel in){
    in.readTypedList(GradeList, GradeDataList.CREATOR);
}


public static class GradeDataList implements Parcelable{

    private String id = "";




    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }



    public GradeDataList(){
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(id);
    }
    public static Parcelable.Creator<GradeDataList> CREATOR = new Creator<GradeDataList>() {

        @Override
        public GradeDataList[] newArray(final int size) {
            return new GradeDataList[size];
        }

        @Override
        public GradeDataList createFromParcel(final Parcel source) {
            return new GradeDataList(source);
        }
    };

    public GradeDataList(final Parcel in){
        id= in.readString();

    }


}

}
于 2015-09-08T04:21:26.527 回答
0

您可以使用普通的 httpclient 或 httpurlconnection

但最好使用 asynckhttp,这是解析 json 数据的最佳选择

你也可以使用一些像jakson(http://jackson.codehaus.org/)这样更快的api

比正常解析

于 2012-09-06T07:53:09.043 回答