Logging into a server using JSON object
I've a bit of code that will be used to login to a clients server
with his user name and password. Here is the 开发者_运维百科code that I am using. My problem is that it isn't authenticating properly. I've checked the URL
, user name & password but still there seems to be some sorta error
public class HttpClient {
private static final String TAG = "&&----HTTPClient-----**";
public static void SendHttpPost (String URL, JSONObject jsonObjSend){
try{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
Log.v("The url is","The url is "+URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPRESPONSE RECIEVED" +(System.currentTimeMillis()-t) + "ms");
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream instream = entity.getContent();
String resultString = convertStreamToString(instream);
Log.v(TAG , "The response is " +resultString);
instream.close();
JSONObject jsonObj = new JSONObject(resultString);
JSONObject sessionJson = jsonObj.getJSONObject("session");
String sessionId = sessionJson.getString("sessionid");
String name = sessionJson.getString("name");
Log.v("The name is"+name,""+sessionId);
}
} catch (Exception e){
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try{
while((line = reader.readLine()) !=null ){
sb.append(line + "\n");
}
}
catch (IOException e){
e.printStackTrace();
} finally{
try {
is.close();
} catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
} }
This is the HOMEACTIVITY
public class HomeActivity extends Activity {
private static final String tag = "##-----HomeActivity-----&&";
private static final String URL = "**************************";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JSONObject jsonObjSend = new JSONObject();
try {
JSONObject header = new JSONObject();
header.put("username","125");
header.put("password","1");
header.put("company", "1000");
jsonObjSend.put("user", header);
// Output the JSON object we're sending to Logcat:
Log.i(tag,"Output the JSON object we're sending to Logcat: " +jsonObjSend.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
At the URL of home activity I am passing the actual server URL (which cannot be shared).
you are not calling the httppost in homeactivity
try this
HttpClient.SendHttpPost(URL, jsonObjSend);
精彩评论