问题
I have login window, where I want to get user information to the next window and share only the username. I both stored password and username in the database and I want to get array result. Here is my code. 2 EditText where i have to get their values and pass them via json. The link I request is ..../userprofiles?username=. so, when I type the username I have to receive basic info. in JSON will be like this:
{
"content": [ {
"id": 4,
"email": "email@domain.com",
"password": "this_will_not_be_set",
"firstName": "John",
"phoneNumber": "11223344",
"username": "newuser",
"birthDate": 1394204315000,
"gender": "Male",
"blacklistedDate": null,
"userPicture": "Oik=",
"blacklisted": false
}],
"size": 25,
"number": 0,
"sort": null,
"totalPages": 1,
"numberOfElements": 1,
"totalElements": 1,
"lastPage": true,
"firstPage": true
}
and my Android code is:
public static String GET(String url) {
InputStream inputStream = null;
String result = "";
try {
HttpClient httpClient = new DefaultHttpClient();
// make GET request to the give URL
HttpResponse httpResponse = httpClient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received", Toast.LENGTH_LONG)
.show();
try {
JSONObject json = new JSONObject(result);
String str = "";
JSONArray jArr = json.getJSONArray("content");
str += "username: " + jArr.getJSONObject(0).getString("username");
str += "password: " + jArr.getJSONObject(0).getString("password");
usernameEditText.setText(str);
passwordEditText.setText(str);
//etResponse.setText(json.toString(1));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Any help will be appreciated! TNX in advance!
回答1:
JumboJey
You can use the following code for the get the result from the http connection
download the follwoing jar file from the link
https://github.com/loopj/android-async-http/raw/master/releases/android-async-http-1.4.4.jar
put jar into lib folder and add follwing code
import com.loopj.android.http.*;
AsyncHttpClient client = new AsyncHttpClient();
client.get("your url", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
try {
JSONObject json = new JSONObject(result);
JSONArray jArr = json.getJSONArray("content");
if(jArr.length>0)
{
JSONObject jobj =jArr.getJSONObject(0);
String username=jobj.getString("username");
String pass=jobj.getString("password");
usernameEditText.setText(str);
passwordEditText.setText(str);
}
} catch (JSONException e) {
e.printStackTrace();
}
});
回答2:
you can try folliwing example for the your json object
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
String jsonstr = "{\n \"content\": [ {\n \"id\": 4,\n \"email\": \"email@domain.com\",\n \"password\": \"this_will_not_be_set\",\n \"firstName\": \"John\",\n \"phoneNumber\": \"11223344\",\n \"username\": \"newuser\",\n \"birthDate\": 1394204315000,\n \"gender\": \"Male\",\n \"blacklistedDate\": null,\n \"userPicture\": \"Oik=\",\n \"blacklisted\": false\n }],\n \"size\": 25,\n \"number\": 0,\n \"sort\": null,\n \"totalPages\": 1,\n \"numberOfElements\": 1,\n \"totalElements\": 1,\n \"lastPage\": true,\n \"firstPage\": true\n}";
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView txt1 = (TextView) rootView.findViewById(R.id.textView1);
TextView txtusername = (TextView) rootView
.findViewById(R.id.textView2);
TextView txtpass = (TextView) rootView.findViewById(R.id.textView3);
try {
JSONObject json = new JSONObject(jsonstr);
JSONArray jArr = json.getJSONArray("content");
if (jArr.length() > 0) {
JSONObject jobj = jArr.getJSONObject(0);
String username = jobj.getString("username");
String pass = jobj.getString("password");
txtusername.setText(username);
txtpass.setText(pass);
}
} catch (JSONException e) {
e.printStackTrace();
}
return rootView;
}
}
}
来源:https://stackoverflow.com/questions/22528789/android-login-input-to-be-send-via-httpget-json-to-server-and-return-list-of-use