改造:如何发出XML请求并获取JSON响应

时间:2018-04-06 19:26:09

标签: android json xml xmlhttprequest retrofit2

我怎么能做一个简单的text / xml POST请求并使用改造2来获取JSON !!! ??? 注1 :我已经知道如何制作JSON GET / POST请求并将JSON作为回复。
note 2 :我有一个端点,其中请求是XML SOAP格式,响应是JSON格式。为了澄清我会在这里发布样品请求回复:

XML示例请求:

    self.scrolled_window = gtk.ScrolledWindow(hexpand=True, vexpand=True)
    self.scrolled_window.set_policy(gtk.PolicyType.NEVER, gtk.PolicyType.AUTOMATIC)


JSON样本回复:

import psutil
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk as gtk
from gi.repository import GObject


class MainWindow(gtk.Window):
    def __init__(self):
        gtk.Window.__init__(self, title="Task Manager")
        self.set_default_size(1000, 500)
        #basic objects in the program
        self.set_border_width(10)
        self.notebook = gtk.Notebook()
        self.grid1 = gtk.Grid(row_spacing=20)
        self.notebook.set_scrollable(True)
        self.add(self.notebook)

        #Processes Tab
        self.tab1 = gtk.Box()
        self.set_border_width(10)
        self.notebook.append_page(self.tab1, gtk.Label("Processes"))

        self.properties = ['name', 'pid', 'username', 'memory_percent', 'cpu_percent']
        p_list = create_list(self.properties, create_list_of_processes())
        print p_list

        #create a list store object for the tree view
        self.process_list_store = gtk.ListStore(str, int, str, str, str)
        for p in p_list:
            self.process_list_store.append(list(p))

        #create a window that can be scrolled
        self.scrolled_window = gtk.ScrolledWindow(hexpand=True, vexpand=True)
        self.scrolled_window.set_policy(gtk.PolicyType.NEVER, gtk.PolicyType.AUTOMATIC)
        self.grid1.attach(self.scrolled_window, 0, 0, 8, 10)

        #create a tree view and add it to the window
        self.tree_view = create_treeview(self.process_list_store)
        self.scrolled_window.add(self.tree_view)
        self.tab1.add(self.grid1)

        GObject.timeout_add_seconds(1, self.update_treeview)

    def update_treeview(self):
        self.process_list_store.clear()
        p_list = create_list(self.properties, create_list_of_processes())
        for p in p_list:
            self.process_list_store.append(list(p))
        return True


#create a list of dictionaries of processes and info about them
def create_list_of_processes():
    list_of_processes = []
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid', 'name', 'username', 'memory_percent', 'cpu_percent'])
        except psutil.NoSuchProcess:
            pass
        else:
            if not pinfo['username']:
                pinfo['username'] = 'SYSTEM'
            pinfo['cpu_percent'] = str(pinfo['cpu_percent'] / psutil.cpu_count()) + '%'
            pinfo['memory_percent'] = str(pinfo['memory_percent'])[0:6]
            pinfo['memory_percent'] = str(pinfo['memory_percent']) + '%'
            list_of_processes.append(pinfo)
    return list_of_processes


#create a tree view object
def create_treeview(process_list_store):
    treeview = gtk.TreeView(process_list_store)
    for i, col_title in enumerate(['Name', 'pid', 'Username', 'Memory usage', 'Cpu usage']):
        renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn(col_title, renderer, text=i)
        column.set_sort_column_id(i)
        column.set_min_width(110)
        column.set_resizable(i)
        treeview.append_column(column)
    return treeview


#create a list based on the desired properties
def create_list(properties, p_dict):
    p_list = []
    for dict in p_dict:
        small_p_list = []
        for prop in properties:
            small_p_list.append(dict[prop])
        p_list.append(small_p_list)
    return p_list


def main():
    window = MainWindow()
    window.connect("delete-event", gtk.main_quit)
    window.show_all()
    gtk.main()

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

我自己找到了答案,实际上是超级容易的。

APIService类:( RequestBody 是此处的关键)

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;

public interface RetrofitAPIService {
//    @Headers("Content-Type: application/json")
    @POST("/webservice.asmx?op=Login")
    Call<RetrofitResponseBody> login(@Body RequestBody body);
}


注意:以下代码的关键是这一行:

RequestBody requestBody = RequestBody.create(MediaType.parse("text/xml"), requestBodyText);

MainActivity.java:

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

        EditText userName = findViewById(R.id.userName);
        EditText password = findViewById(R.id.password);

        RetrofitAPIService mAPIService = RetrofitAPIUtils.getRetrofitAPIService();

        String requestBodyText = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n" +
                "  <soap12:Body>\n" +
                "    <Login xmlns=\"http://tempuri.org/\">\n" +
                "      <username>" + userName.getText() + "</username>\n" +
                "      <password>" + password.getText() + "</password>\n" +
                "    </Login>\n" +
                "  </soap12:Body>\n" +
                "</soap12:Envelope>";
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/xml"), requestBodyText);
        Call<RetrofitResponseBody> response = mAPIService.login(requestBody);

        response.enqueue(new Callback<RetrofitResponseBody>() {
            @Override
            public void onResponse(Call<RetrofitResponseBody> call, Response<RetrofitResponseBody> response) {
                try {
                    Log.d("JavadR:",
                            response.body().getUserID().toString() +
                                    " - " +
                                    response.body().getFailureText()
                    );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<RetrofitResponseBody> call, Throwable t) {

            }
        });

    }

RetrofitResponseBody 并不是太重要,但为了保持一致性和方便性,我将在此处发布:

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class RetrofitResponseBody {

    @SerializedName("UserID")
    @Expose
    private Integer userID;
    @SerializedName("FailureText")
    @Expose
    private Object failureText;
    @SerializedName("UserValidPasswordCode")
    @Expose
    private Integer userValidPasswordCode;
    @SerializedName("UserPatientIsActiveWithNationalIDCode")
    @Expose
    private Boolean userPatientIsActiveWithNationalIDCode;

    public Integer getUserID() {
        return userID;
    }

    public void setUserID(Integer userID) {
        this.userID = userID;
    }

    public Object getFailureText() {
        return failureText;
    }

    public void setFailureText(Object failureText) {
        this.failureText = failureText;
    }

    public Integer getUserValidPasswordCode() {
        return userValidPasswordCode;
    }

    public void setUserValidPasswordCode(Integer userValidPasswordCode) {
        this.userValidPasswordCode = userValidPasswordCode;
    }

    public Boolean getUserPatientIsActiveWithNationalIDCode() {
        return userPatientIsActiveWithNationalIDCode;
    }

    public void setUserPatientIsActiveWithNationalIDCode(Boolean userPatientIsActiveWithNationalIDCode) {
        this.userPatientIsActiveWithNationalIDCode = userPatientIsActiveWithNationalIDCode;
    }

}