如何在改造中发送JSONObject请求?

时间:2017-07-05 08:40:35

标签: android json post android-volley retrofit2

我试图使用改造发送JSONObject请求(POST方法)并将结果作为JSONObject获取,我该如何实现。我的内容类型是(application / json) 你能分享一些最好的方法吗?

改造界面类

public interface RequestClient {
@Headers("Content-Type: application/json")
@POST("TripmakersLowFareShopping")
Call<FlightResponse>pushRequest(@Body FlightRequest request);  }

请求模型类

public class FlightRequest {

@SerializedName("AgencyID")
@Expose
private String agencyID;
@SerializedName("BranchID")
@Expose
private String branchID;
@SerializedName("OriginDestinationInformations")
@Expose
private ArrayList<OriginDestinationInformation> originDestinationInformations = null;
@SerializedName("PassengerTypeQuantities")
@Expose
private ArrayList<PassengerTypeQuantity> passengerTypeQuantities = null;
@SerializedName("Password")
@Expose
private String password;
@SerializedName("PricingSourceType")
@Expose
private Integer pricingSourceType;
@SerializedName("RequestOptions")
@Expose
private Integer requestOptions;
@SerializedName("SessionId")
@Expose
private Object sessionId;
@SerializedName("SupplierParameterList")
@Expose
private ArrayList<SupplierParameterList> supplierParameterList = null;
@SerializedName("Target")
@Expose
private Integer target;
@SerializedName("TravelPreferences")
@Expose
private TravelPreferences travelPreferences;
@SerializedName("UserName")
@Expose
private String userName;

/**
 * No args constructor for use in serialization
 * 
 */

public FlightRequest() {
    super();
    this.agencyID = "20083";
    this.branchID = "10161";
    this.password = "Tj9%2f30XvS59GOBsjHuMd%2bg%3d%3d";
    this.pricingSourceType = 0;
    this.requestOptions = 0;
    this.sessionId = null;
    this.target = 0;
    this.userName = "qc@*****.com";
}

public String getAgencyID() {
    return agencyID;
}

public void setAgencyID(String agencyID) {
    this.agencyID = agencyID;
}

public String getBranchID() {
    return branchID;
}

public void setBranchID(String branchID) {
    this.branchID = branchID;
}

public List<OriginDestinationInformation> getOriginDestinationInformations() {
    return originDestinationInformations;
}

public void setOriginDestinationInformations(ArrayList<OriginDestinationInformation> originDestinationInformations) {
    this.originDestinationInformations = originDestinationInformations;
}

public List<PassengerTypeQuantity> getPassengerTypeQuantities() {
    return passengerTypeQuantities;
}

public void setPassengerTypeQuantities(ArrayList<PassengerTypeQuantity> passengerTypeQuantities) {
    this.passengerTypeQuantities = passengerTypeQuantities;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public Integer getPricingSourceType() {
    return pricingSourceType;
}

public void setPricingSourceType(Integer pricingSourceType) {
    this.pricingSourceType = pricingSourceType;
}

public Integer getRequestOptions() {
    return requestOptions;
}

public void setRequestOptions(Integer requestOptions) {
    this.requestOptions = requestOptions;
}

public Object getSessionId() {
    return sessionId;
}

public void setSessionId(Object sessionId) {
    this.sessionId = sessionId;
}

public List<SupplierParameterList> getSupplierParameterList() {
    return supplierParameterList;
}

public void setSupplierParameterList(ArrayList<SupplierParameterList> supplierParameterList) {
    this.supplierParameterList = supplierParameterList;
}

public Integer getTarget() {
    return target;
}

public void setTarget(Integer target) {
    this.target = target;
}

public TravelPreferences getTravelPreferences() {
    return travelPreferences;
}

public void setTravelPreferences(TravelPreferences travelPreferences) {
    this.travelPreferences = travelPreferences;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

} 响应模型类

public class FlightResponse {


private JSONObject responceData;


public JSONObject getResponceData() {
    return responceData;
}

public void setResponceData(JSONObject responceData) {
    this.responceData = responceData;
}

}

改装声明和功能部分

   rqbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ArrayList<OriginDestinationInformation> originlist = new ArrayList<>();
            originlist.add(new OriginDestinationInformation(null,"/Date(1503599400000)/",null,"COK","DXB"));
            ArrayList<PassengerTypeQuantity> typeQuantities = new ArrayList<>();
            ArrayList<SupplierParameterList>supplierParameterLists = new ArrayList<SupplierParameterList>();
            supplierParameterLists.add(new SupplierParameterList(false,"EndUserIPAddress","61.0.250.97"));
            supplierParameterLists.add(new SupplierParameterList(false,"EndUserBrowserAgent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"));
            supplierParameterLists.add(new SupplierParameterList(false,null,null));
            supplierParameterLists.add(new SupplierParameterList(false,"UserData","qc@tripmakers.com,971_527564545,Fateh"));
            supplierParameterLists.add(new SupplierParameterList(false,"RequestOrigin","US-localhost"));

            typeQuantities.add(new PassengerTypeQuantity(1,1));
            TravelPreferences travelPreferences = new TravelPreferences(1,1);
            FlightRequest request = new FlightRequest();
            request.setOriginDestinationInformations(originlist);
            request.setPassengerTypeQuantities(typeQuantities);
            request.setTravelPreferences(travelPreferences);
            request.setSupplierParameterList(supplierParameterLists);

            requestCall(request);
        }
    });
}

private void requestCall(FlightRequest request) {
     OkHttpClient.Builder httpClient ;

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://192.168.1.125:8013/flight/").addConverterFactory(GsonConverterFactory.create());
    Retrofit retrofit = builder.build();
    RequestClient client = retrofit.create(RequestClient.class);

    Call<FlightResponse> requestCall = client.pushRequest(request);
    requestCall.enqueue(new Callback<FlightResponse>() {
        @Override
        public void onResponse(Call<FlightResponse> call, Response<FlightResponse> response) {
            Toast.makeText(RetrofitResults.this, "Sucess", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<FlightResponse> call, Throwable t) {
            Toast.makeText(RetrofitResults.this, "Something went wrong", Toast.LENGTH_SHORT).show();
        }
    });
}

2 个答案:

答案 0 :(得分:1)

你可以看到this link  完整的请求/响应类型以及如何发送requset和其他改装调用示例。

这是一个完全正常工作的例子service request

1.在为改造添加依赖项之后,首先创建您的改造serviceGenerator

public class ServiceGenerator {

//main donate server
private static final String SERVICE_BASE_URL = "127.0.0.1"; //add your server ip here
private static Retrofit retrofit;
private static OkHttpClient.Builder httpClient ;
private static ServiceGenerator instance;
private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(SERVICE_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create());

private ServiceGenerator() {
    init();
}

public static ServiceGenerator getInstance() {

    if (instance == null) {
        instance = new ServiceGenerator();
    }
    return instance;
}

public static <S> S createService(Class<S> serviceClass) {
    return retrofit.create(serviceClass);
}

public static void init(){
    httpClient =new OkHttpClient.Builder()
            .sslSocketFactory(getSSLConfig(KarizApplication.appContext).getSocketFactory());

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(Config.HTTP_LOG_LEVEL);

    httpClient.addInterceptor(logging);
    httpClient.connectTimeout(50, TimeUnit.SECONDS);
    httpClient.readTimeout(50, TimeUnit.SECONDS);
    OkHttpClient client = httpClient.build();
    retrofit = builder.client(client).build();
}
    public static Retrofit retrofit() {
    return retrofit;
}

private static SSLContext getSSLConfig(Context context) {
    try {
        // Loading CAs from an InputStream
        CertificateFactory cf = null;
        cf = CertificateFactory.getInstance("X.509");

        Certificate ca;
        // I'm using Java7. If you used Java6 close it manually with finally.
        InputStream cert = context.getResources().openRawResource(R.raw.donate_apache_selfsigned);
        ca = cf.generateCertificate(cert);

        // Creating a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);

        // Creating a TrustManager that trusts the CAs in our KeyStore.
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Creating an SSLSocketFactory that uses our TrustManager
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

        return sslContext;
    }
    catch (Exception e){
        throw new RuntimeException(e);
    }
}

}
  1. 之后,您需要创建所需的servicerequest / response类:

    public interface UserProfileServices {
    
    @POST("setting/update")
    Call<SettingsResponse> saveSettings(@Body SettingsRequest settingsRequest);
      }
    
  2. SettingRequest上课:

    public class SettingsRequest {
    @SerializedName("id")
    @Expose
    private String userId;
    @SerializedName("settings")
    @Expose
    private String settingsData;
    
    public String getUserId() {
    return userId;
    }
    
    public void setUserId(String userId) {
    this.userId = userId;
    }
    
    public String getSettingsData() {
    return settingsData;
    }
    
    public void setSettingsData(String settingsData) {
    this.settingsData = settingsData;
    }
    }
    
  3. SettingResponse上课:

    public class SettingsResponse  {
    @SerializedName("settings")
    @Expose
    private JSONObject settingsData;
    public JSONObject getSettingsData() {
    return settingsData;
    }
    
    public void setSettingsData(JSONObject settingsData) {
    this.settingsData = settingsData;
    }
    }
    
  4. 用法如下:

     private void sendSettingsToServer(Settings setting) {
    final SettingsRequest settingsRequest = new SettingsRequest();
    settingsRequest.setUserId(KarizApplication.getUserId());
    settingsRequest.setSettingsData(setting.getSettingsData().toString());
    userProfileServices = ServiceGenerator.getInstance().createService(UserProfileServices.class);
    Call<SettingsResponse> saveSettings = userProfileServices.saveSettings(settingsRequest);
    saveSettings.enqueue(new Callback<SettingsResponse>() {
        @Override
        public void onResponse(Call<SettingsResponse> call, Response<SettingsResponse> response) {
            if (response.isSuccessful()) {
                Log.d("saveSettings", "successful");
            } else {
                if (response.code() < 500) {} 
                else {}
            }
        }
    
        @Override
        public void onFailure(Call<SettingsResponse> call, Throwable t) {
    
            }
        }
    });
    }
    
  5. 希望这会有所帮助。

答案 1 :(得分:0)

在您的Activity或片段中,您可以为结果onSuccess或onFail实现ServiceCallBack,并且可以调用如下方法:

//service call
public void callRoadTrafficIncident(JSONObject jsonObject) {
    try {

        BaseRequest baseRequest = new BaseRequest(this);
        baseRequest.setServiceCallBack(this);
        baseRequest.setRequestTag(UrlFactory.SAVERTI);
        Api api = (Api) baseRequest.execute(Api.class);
        if (api != null) {
            TypedInput requestBody = new TypedByteArray(
                    "application/json", jsonObject.toString().getBytes(Charset.forName("UTF-8")));
            api.saveRTI(requestBody, baseRequest.requestCallback());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

对于Api界面,您可以创建如下:

public interface Api {


    @Headers({"Content-Type:application/json"})
    @POST("/saveRTI")
    public void saveRTI(@Body TypedInput jsonObject, Callback<String> callback);}

对于baseRequest类:

public class BaseRequest {

    private int requestTag;
    private boolean progressShow = true;
    private ServiceCallBack serviceCallBack;
    private RestClient restClient;
    private Context context;
    private Callback<Object> callback;

    public BaseRequest(Context context){
        this.context = context;
        setProgressShow(progressShow);
    }

    public Object execute(Class classes){
        if(Utils.getConnectivityStatus(context)){
            restClient=  new RestClient(context,this);
            return restClient.execute(classes);
        }else{

            //Utils.showToast(context, "Network is not available.");
            return null;
        }
    }

    public Callback<String> requestCallback(){

        return restClient.callback;
    }
    public Callback<Object> getCallback() {
        return callback;
    }

    public void setCallback(Callback<Object> callback) {
        this.callback = callback;
    }

    public RestClient getRestClient() {
        return restClient;
    }

    public void setRestClient(RestClient restClient) {
        this.restClient = restClient;
    }

    public ServiceCallBack getServiceCallBack() {
        return serviceCallBack;
    }

    public void setServiceCallBack(ServiceCallBack serviceCallBack) {
        this.serviceCallBack = serviceCallBack;
    }

    public int getRequestTag() {
        return requestTag;
    }

    public void setRequestTag(int requestType) {
        this.requestTag = requestType;
    }

    public boolean isProgressShow() {
        return progressShow;
    }

    public void setProgressShow(boolean progressShow) {
        this.progressShow = progressShow;
    }

}

对于RestClient调用类:

public class RestClient {



    private BaseRequest baseRequest;
    private ProgressDialog pDialog = null;
    private Context context;

    public RestClient(Context context, BaseRequest _baseRequest) {
        this.baseRequest = _baseRequest;
        this.context = context;
    }

    public Object execute(Class classes) {
        if (baseRequest.isProgressShow())
            showProgressDialog(context);
        return setUpRestClient(classes);
    }

    private Object setUpRestClient(Class apiClasses) {

        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setReadTimeout(120, TimeUnit.SECONDS);
        okHttpClient.setConnectTimeout(120, TimeUnit.SECONDS);

        RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(UrlFactory.BASE_URL)
                .setRequestInterceptor(new SessionRequestInterceptor(context))
                .setClient(new OkClient(okHttpClient));

        builder.setConverter(new StringConverter());
        RestAdapter restAdapter = builder.build();
        return restAdapter.create(apiClasses);
    }

    public Callback<String> callback = new Callback<String>() {

        @Override
        public void success(String o, Response response) {
            if (o != null && !o.isEmpty())
            baseRequest.getServiceCallBack().onSuccess(baseRequest.getRequestTag(), o);
            dismissProgressDialog();

        }

        @Override
        public void failure(RetrofitError error) {
            baseRequest.getServiceCallBack().onFail(error);
            dismissProgressDialog();
        }

    };

    public void showProgressDialog(Context context) {
        try {
            if (((Activity) context).isFinishing()) {
                return;
            }
            pDialog = new ProgressDialog(context);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissProgressDialog() {
        try {
            if (pDialog != null)
                pDialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    class StringConverter implements Converter {

        @Override
        public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
            String text = null;
            try {

                text = fromStream(typedInput.in());
            } catch (IOException ignored) {
                ignored.printStackTrace();
            }
            return text;
        }

        @Override
        public TypedOutput toBody(Object o) {

            return null;
        }

        private String fromStream(InputStream in) throws IOException {

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder out = new StringBuilder();
            String newLine = System.getProperty("line.separator");
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
                out.append(newLine);
            }
            return out.toString();
        }
    }

}

用于服务回调界面

public interface ServiceCallBack
{
    public void onSuccess(int tag, String baseResponse);
    public void onFail(RetrofitError error);
}

对于SessionRequest Intercepter

public class SessionRequestInterceptor implements RequestInterceptor {
    private Context context;

    public  SessionRequestInterceptor(Context context){
        this.context = context;
    }
    @Override
    public void intercept(RequestFacade request) {
    request.addHeader("Content-Type", "application/json");
    request.addHeader("accept", "application/json");
    }
}