使用HttpPost从android客户端应用程序向java web服务方法传递参数时出错

使用HttpPost从android客户端应用程序向java web服务方法传递参数时出错,java,android,web-services,http-post,Java,Android,Web Services,Http Post,我想从android客户端应用程序向java web服务传递参数。但是我犯了一个错误。我的java web服务代码如下: public class JsonWebService { @POST @Path("getData") public String getData(String category) throws Exception { JSONObject jsonData = new JSONObject(); String Ema

我想从android客户端应用程序向java web服务传递参数。但是我犯了一个错误。我的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();
}
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";
                    StringEntity params = new StringEntity("{\"category\":\"Marketing\"}");
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost post = new HttpPost(URL);
                    post.setEntity(params);

                    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();
            }
        });
}
我的android客户端代码如下所示:

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();
}
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";
                    StringEntity params = new StringEntity("{\"category\":\"Marketing\"}");
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost post = new HttpPost(URL);
                    post.setEntity(params);

                    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();
            }
        });
}
btncategray=(按钮)findViewById(R.id.button1);
txtCategory=(EditText)findViewById(R.id.editText1);
gridV=(GridView)findviewbyd(R.id.gridView1);
txtName=(EditText)findViewById(R.id.editText3);
txtEmail=(EditText)findViewById(R.id.editText2);
btncategray.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
线程netThread=新线程(){
公开募捐{
试一试{
最终JSONObject receivedJson;/=新JSONObject();
字符串URL=”http://192.168.1.7:8080/JsonWebService/services/JsonWebService/getData";
StringEntity参数=新的StringEntity(“{\”类别\“:\”营销\“}”);
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost=新的HttpPost(URL);
post.setEntity(params);
HttpResponse httpres=httpClient.execute(post);
HttpEntity entity=httpres.getEntity();
字符串json=EntityUtils.toString(entity.toString();
字符串部分[]=json.split(“”);
零件=零件[1]。拆分(“”);
字符串jsonPart=parts[0];
receivedJson=新的JSONObject(jsonPart);
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
试一试{
setText(receivedJson.getString(“名称”));
setText(receivedJson.getString(“电子邮件”));
}
捕获(例外e){
}
}
};
netThread.start();
}
});
}
我遇到以下错误:

Caused by: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '{' (code 123) in prolog; expected '<' at [row,col {unknown-source}]: [1,1]
at com.ctc.wstx.sr.StreamScanner.throwUnexpectedChar(StreamScanner.java:648)
at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2047)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1069)
at org.apache.axiom.util.stax.wrapper.XMLStreamReaderWrapper.next(XMLStreamReaderWrapper.java:225)
at org.apache.axiom.om.impl.builder.StAXOMBuilder.parserNext(StAXOMBuilder.java:668)
at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:214)
   ... 26 more
[INFO] Remaining input stream :[]

原因:com.ctc.wstx.exc.WstxUnexpectedCharException:prolog中意外的字符“{”(代码123);应为“您的webservice方法不应将json作为输入媒体类型

利用JAX-RS规范的@Consumes和@products注释来告诉您的服务期望和交付的内容:

@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")

您可能还需要将jersey json库包含到您的项目中。

当您尝试从普通web浏览器访问web服务时,尝试使用invokeHttpDoes来删除您的web服务工作?—有一些很棒的google chrome应用程序可用于测试web服务(例如)