我想从android app执行java web服务方法。我的Web服务方法签名如下:
public String getData(String category) throws Exception
该方法返回string并接受一个字符串作为参数。
我已经从google chrome的地址栏执行了该方法:
http://localhost:8080/JsonWebService/services/JsonWebService/getData?category=Marketing
这里getData是方法的名称,Marketing是该方法的参数。从资源管理器中它运行良好。
但是当我向Android应用程序的httppost请求添加相同的url时,它无法说出错误的参数数量。我的Android应用程序代码是:
HttpPost post = new HttpPost("http://192.168.1.7:8080/JsonWebService/services/JsonWebService/getData?category=Marketing");
HttpResponse httpres = httpClient.execute(post);
请注意:这里需要192.168.1.7,因为我直接在设备上执行应用程序,因此我没有使用localhost。
非参数方法也可以从Android应用程序正确执行。 但是当在url中插入参数时,为什么它在android应用程序中错误地说错误的参数数量以及它如何在PC上的谷歌浏览器中正确执行。请帮忙......谢谢...
我在这里添加代码。我的java Web服务代码如下:
public class JsonWebService {
@POST
@Path("getData")
public String getData(String category) throws Exception {
JSONObject jsonData = new JSONObject();
String Email = "";
String Name = "";
String receivedCat = "";
boolean status = false;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/admindb","root","");
java.sql.PreparedStatement query = con.prepareStatement("SELECT * FROM sample WHERE Category =" + "'" + category + "'" + ";");
ResultSet result = query.executeQuery();
while(result.next()){
receivedCat = result.getString("Category");
Name = result.getString("Name");
Email = result.getString("Email");
}
if(receivedCat.equals(category)){
status = true;
jsonData.put("Name",Name);
jsonData.put("Email", Email);
jsonData.put("status", status);
}
}
catch(Exception e) {
e.printStackTrace();
}
return jsonData.toString();
}
我的Android客户端代码如下所示:
btnCategory = (Button)findViewById(R.id.button1);
txtCategory = (EditText)findViewById(R.id.editText1);
gridV = (GridView)findViewById(R.id.gridView1);
txtName = (EditText)findViewById(R.id.editText3);
txtEmail = (EditText)findViewById(R.id.editText2);
btnCategory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread netThread = new Thread() {
public void run() {
try {
final JSONObject receivedJson;// = new JSONObject();
String URL = "http://192.168.1.7:8080/JsonWebService/services/JsonWebService/getData?category=Marketing?";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
HttpResponse httpres = httpClient.execute(post);
HttpEntity entity = httpres.getEntity();
String json = EntityUtils.toString(entity).toString();
String parts[] = json.split("<ns:return>");
parts = parts[1].split("</ns:return>");
String jsonPart = parts[0];
receivedJson = new JSONObject(jsonPart);
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
txtName.setText(receivedJson.getString("Name"));
txtEmail.setText(receivedJson.getString("Email"));
}
catch(Exception e){
}
}
};
netThread.start();
}
});
}
问题出在String Client中的java客户端,它是调用java Web服务方法的URL字符串。请帮帮我......