【发布时间】:2019-11-23 01:19:01
【问题描述】:
为什么我的改造代码不能在数据库中插入数据?我在 iis 上发布了我的 wcf 服务,当我在浏览器中传递参数时它工作正常。
这是我的界面代码:
interface ApiInterface {
@POST("client")
Call<client>insert(@Body client cl);
}
这是我的模型类:
public client(String name, String contact, String addres) {
this.name = name;
this.contact = contact;
this.addres = addres;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
这是主要活动:
textname = (EditText) findViewById(R.id.name);
textcontact = (EditText) findViewById(R.id.contact);
textpssword = (EditText) findViewById(R.id.password);
Button btn = findViewById(R.id.send);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
client cl=new client(textname.getText().toString(),
textcontact.getText().toString(),textpssword.getText().toString());
sendNetworkrequest(cl);
}
});
}
private void sendNetworkrequest(client cl){
Retrofit.Builder builder=new
Retrofit.Builder().baseUrl("http://192.168.1.20/Service1.svc/").
addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit=builder.build();
ApiInterface apiInterface=retrofit.create(ApiInterface.class);
Call<client> call=apiInterface.insert(cl);
call.enqueue(new Callback<client>() {
@Override
public void onResponse(Call<client> call, Response<client>
response) {
Toast.makeText(MainActivity.this,"compl
inserted",Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<client> call, Throwable t) {
Toast.makeText(MainActivity.this, "some thing went wrng",
Toast.LENGTH_SHORT).show();
}
});
我可以通过baseurl的写入格式吗?
这在浏览器中运行良好
http://192.168.1.20:8080/Service1.svc/insert?name=mehmood&contact=123&addres=lahore
是本地发布的地址。 insert 是 wcf 服务中定义的函数。
【问题讨论】:
-
您的插入方法在 WCF 中定义为使用 http-get,通常使用 [webget] 属性进行修饰。所以我们在构造HTTP请求时,应该使用查询字符串而不是请求体来传递参数(实体的属性)
-
完全正确.... [OperationContract] [WebInvoke (Method="GET",ResponseFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Wrapped,RequestFormat=WebMessageFormat.Json,UriTemplate="/insert?name ={name}&contact={cont}&addres={addr}")] string insert(string name, string cont, string addr);那我做什么
-
如果构造的http请求是POST并附加一个JSON请求体,我们可以像下面这样定义OperationContract, [OperationContract] [WebInvoke(Method ="POST",RequestFormat =WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json,BodyStyle =WebMessageBodyStyle.Bare)] String InSertProduct(Product p); [DataContract] public class Product { [DataMember] public int ID { get;放; } [DataMember] 公共字符串名称 { 获取;放; } }