从android发送JSON字符串到RESTful Web服务

时间:2015-12-18 13:00:08

标签: java android json netbeans

我正在尝试使用JSON字符串和Restful Web服务在我的Android应用程序中创建一个简单的登录/登录表单。 如果我手动将JSON数据放在NetBeans IDE端,但不知道如何使用新的用户名和密码将数据发送回Web服务以创建新用户,则登录正在运行。

我使用JSON数组的AsyncTask:

    private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... urls) {
        return readJSONFeed(urls[0]);// as a json string : [{},{},{},{}]
    }

    protected void onPostExecute(String result) {
        try {
            JSONArray jsonArray = new JSONArray(result);

            // ---check user name and password---

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject obj = jsonArray.getJSONObject(i);

                if (obj.getString("User Name").equals(user.getUserName())
                        && obj.getString("Password").equals(
                                user.getPassword())) {
                    userNameAndPasswordCorrect = true;
                    break;
                }
            }
            if (userNameAndPasswordCorrect) {
                changeActivity(MenuScreen.class);
                userNameAndPasswordCorrect = false;
            } else {
                new AlertDialog.Builder(WelcomeScreen.this)
                        .setTitle("Wrong Details")
                        .setMessage(
                                "One or more of your details is incorrect\nPlease try again")
                        .setPositiveButton("O.K",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog,
                                            int which) {
                                    }
                                }).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

readJSONFeed:

public String readJSONFeed(String URL) {

    Log.d("JSON", "readJSONFeed");
    StringBuilder stringBuilder = new StringBuilder();

    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(URL);

    try {

        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();

        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(content));
            String line;

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } else {
            Log.e("JSON", "Failed to download file");
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return stringBuilder.toString();
}

NetBeans IDE代码:

@Path("generic")
public class GenericResource {

@Context
private UriInfo context;

/**
 * Creates a new instance of GenericResource
 */
public GenericResource() {
}

/**
 * Retrieves representation of an instance of com.it.as.GenericResource
 * @return an instance of java.lang.String
 */
@GET
@Produces("application/json")
public String getJson() {
JsonArrayBuilder value = Json.createArrayBuilder();
JsonObject jo1 = Json.createObjectBuilder()
.add("User Name", "aaa")
.add("Password", "12345").build();
value.add(jo1);

JsonObject jo2 = Json.createObjectBuilder()
.add("User Name", "bbb")
.add("Password", "98765").build();
value.add(jo2);
return value.build().toString();
}
/**
 * PUT method for updating or creating an instance of GenericResource
 * @param content representation for the resource
 * @return an HTTP response with content of the updated or created resource.
 */
@PUT
@Consumes("application/json")
public void putJson(String content) {
}
}

谢谢, 阿米特。

0 个答案:

没有答案