How to get info from HttpResponse java? - java

First of all please look at my code below:
List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
qsList.add(new BasicNameValuePair("oauth_token", accessToken));
String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
HttpGet userInfoRequest = new HttpGet(id + "?" + queryString);
DefaultHttpClient defaultHttpClientclient = new DefaultHttpClient();
HttpResponse userInfoResponse;
try {
userInfoResponse = defaultHttpClientclient.execute(userInfoRequest);
String responseBody = EntityUtils.toString(userInfoResponse.getEntity());
System.out.println("User info response: " + responseBody);
System.out.println("");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I got an access token from Salesforce. Now I request user's information via that token. In the responseBody I got all infomation of that user like username, id, language,... Now I need to take only username from the response. What should I do to take it?

The response is likely in JSON. If so you can parse the data you need. I won't repost the code, instead please see: How to parse JSON in Java
JSONObject responseJSON = new JSONObject(EntityUtils.toString(userInfoResponse.getEntity());
String username = responseJSON.getString("username");

Related

Odata V4 Client: getEntityCreate method

I developed an ODataClient in Java in order to create new entities. I am encountering difficulties to create new entities. I took the initiative to see all messages sent by my client with Fiddler.
ODataEntityCreateRequest<ClientEntity> request=
client.getCUDRequestFactory()
.getEntityCreateRequest(new URI("http://localhost:8888/"), clientEntity);
request.addCustomHeader("Content-Type", "application/json;odata.metadata=minimal");
request.setAccept("application/json;odata=minimalmetadata");
ODataEntityCreateResponse<ClientEntity> response = request.execute();
below the first line of the body I obtained with Fiddler:
17b
{"#odata.type":"#ODataDemo.Product", ....}
I tested manually with Fiddler to create a new entity and the first line of message body should be:
{"odata.type":"ODataDemo.Product", ....}
I would like to know if it possible to set the body of the request with Odata in order to delete "#" and "#".
Thanks,
I found an alternative solution to this problem. I do not use entirely OData libraries. I created methods to to the post Request.
public void insertData(String entityName, Entity entity)
{
try {
ResWrap<Entity> resW = new ResWrap<Entity>(new URI(this.baseURI.concat("/").concat(entityName)), "full", entity);
ClientEntity clientEntity = this.client.getBinder().getODataEntity(resW);
//String message = getMessageRebuild(client.getWriter().writeEntity(clientEntity, ContentType.APPLICATION_JSON));
InputStream is = client.getWriter().writeEntity(clientEntity, ContentType.APPLICATION_JSON);
if(is != null)
{
System.out.println("POST: "+post(this.baseURI.concat("/").concat(entityName), is));
//System.out.println("POST:"+post("http://localhost:8888/"+entityName, is));
}
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ODataSerializerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String post(String url,InputStream message) throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
//post.addHeader("Content-Type", "application/json;odata.metadata=minimal");
//post.addHeader("Accept", "application/json;odata=verbose");
post.addHeader("Content-Type", "application/json");
post.addHeader("Accept", "application/json");
HttpEntity entity = new ByteArrayEntity(IOUtils.toByteArray(message));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
return result;
}
insertData take two parameters : entityName + Entity I generated.
I use the librairie org.apache.http to send the http message to the OData Server.

Android: cannot instantiate the type httpclient

I am getting an error with the following line of code
HttpClient Client= new HttpClient, event I have add httpclient-4.2.3.jar to my project.
I have tried rewriting it as HttpClient Client= new DefaultHttpClient. But it solves the problem and creates a new error with other methods (in executeMethod()).
This is my code :
public static String POSTUpload(String url, String foto){
InputStream inputStream=null;
String result="";
HttpClient httpClient = new HttpClient();
PostMethod method = new PostMethod(url);
//set JSON ke hhtp post entity
// File file_foto= new File(foto);
// FileEntity fe_foto=new FileEntity(file_foto, "image/jpeg");
method.setRequestEntity(new FileRequestEntity(new File(foto), "multipart/form-data"));
// se.setContentType("application/json;charset=UTF-8");
// httpPost.setHeader("Accept", "application/json");
try {
int status = httpClient.executeMethod(method);
System.out.println("HTTP status " + method.getStatusCode()
+ " creating con\n\n");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); // TODO Auto-generated catch block
}finally {
method.releaseConnection();
}
}
is there anyone know why this is happen? Please Help

Adding new user to KeyStone-OpenStack using Android

I'm trying to create new user to OpenStack using the api given in this link
http://docs.openstack.org/api/openstack-identity-service/2.0/content/POST_addUser_v2.0_users_Admin_API_Service_Developer_Operations-d1e1356.html
I have passed the token replied by the server when I logged-in.
This is my code for creating new user:
Log.i("TAG","Adding new User");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.1.122:35357/v2.0/users");
try {
JSONObject newuser = new JSONObject();
JSONObject userInfo = new JSONObject();
newuser.put("user", userInfo);
//end of JsonArray
userInfo.put("username", "Lou Mary");
userInfo.put("email", "lagojo#owtel.com");
userInfo.put("enabled", true);
userInfo.put("OS-KSADM:password", "secret101");
Log.i("TAG", "passing your data"+newuser.toString());
// erequest.setText(auth.toString());
StringEntity params1 = new StringEntity(newuser.toJSONString());
params1.setContentEncoding("UTF-8");
//params1.setContentType("application/json");
Log.i("TAG","params" +params1);
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("X-Auth-Token", "MIICbgYJKoZIhvcNAQcCoIICXzCCAlsCAQExCTAHBgUrDgMCGjCCAUcGCSqGSIb3DQEHAaCCATgEggE0eyJhY2Nlc3MiOiB7InRva2VuIjogeyJpc3N1ZWRfYXQiOiAiMjAxMy0xMS0yMlQwMDo1NjoxMy42NDI2NjkiLCAiZXhwaXJlcyI6ICIyMDEzLTExLTIzVDAwOjU2OjEzWiIsICJpZCI6ICJwbGFjZWhvbGRlciJ9LCAic2VydmljZUNhdGFsb2ciOiBbXSwgInVzZXIiOiB7InVzZXJuYW1lIjogImFkbWluIiwgInJvbGVzX2xpbmtzIjogW10sICJpZCI6ICJjY2MwMjJkZGNhMzU0N2NiYmIxMmZmNTViNTZkOGI2OCIsICJyb2xlcyI6IFtdLCAibmFtZSI6ICJhZG1pbiJ9LCAibWV0YWRhdGEiOiB7ImlzX2FkbWluIjogMCwgInJvbGVzIjogW119fX0xgf8wgfwCAQEwXDBXMQswCQYDVQQGEwJVUzEOMAwGA1UECBMFVW5zZXQxDjAMBgNVBAcTBVVuc2V0MQ4wDAYDVQQKEwVVbnNldDEYMBYGA1UEAxMPd3d3LmV4YW1wbGUuY29tAgEBMAcGBSsOAwIaMA0GCSqGSIb3DQEBAQUABIGAqoSsewZ+ceYq1JXnu9OVvTJj+Aljm+rUio1biXow72iZ+MVBJKbKvlT4-2DFPC1PrCOErpX2jJ7HuiASSaBgAcROT+LmV3KNnHa+p9DCtgSBGRN7qHJpnQBXgs3tz4ZMVi3AB9i1mOmVHxeVKVfiQWt1zyis7OZPG-PZRq1DohQ=");
httppost.setEntity((params1));
// Execute HTTP Post Request
Log.i("TAG", "pushing your data");
HttpResponse response = httpclient.execute(httppost);
Log.i("TAG", "Sucessful " + response.getParams());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonresponse = reader.readLine();
JSONTokener tokener = new JSONTokener(jsonresponse);
try {
JSONArray finalResult = new JSONArray(tokener);
Log.i("TAG", "Sucessfully communicated on server");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch (IOException e) {
Log.e("", "IOException " + e.toString());
Log.i("", "The server refused again! ");
// TODO Auto-generated catch block
}
}
But I'm getting this Error
org.json.JSONException: Value{
"error": {
"message": "The request you have made requires authentication.",
"title": "Not Authorized",
"code": 401
} }
I'm expecting that the token I've passed will authorize me from adding new user.
That's why I don't understand the error.
Anyone, please help. Any idea how to solve this?
Apart from checking that you have the Admin role for the target project (e.g. when you request the auth token, you need to specify the tenant ID), also make sure that the auth token is not expired.
Also I believe you should use
"name", "Lou Mary"
instead of
"username", "Lou Mary"

Error HTTP 422 GET in Android

I'm trying to perform a GET request to the server that returns me a JSON file. But I am getting an error in the HTTP statusLine / 422. Anyone know why. Below I show how I'm doing
public void testConverteArquivoJsonEmObjetoJava() {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(
"http://safe-sea-4024.ppooiheroku4554566adffasdfasdfalaqwerpcp.com/crimes/mobilelist");
get.setHeader("Accept", "application/json");
get.setHeader("Content-type", "application/json");
get.getParams()
.setParameter("token",
"0V1AYFK12SeCZHYgXbNMew==$tRqPNplipDwtbD0vxWv6GPJIT6Yk5abwca3IJ88888a6JhMs=");
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(get);
String jsonDeResposta = EntityUtils.toString(httpResponse
.getEntity());
System.out.println();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Usually you do not specify a Content-Type header with a GET request. This header tells the server how to interpret the entity includes in the message. It is possible that the server side is expecting a JSON entity even though GET cannot include a body. Try removing the Content-Type header.
I tried the URL that you cleverly changed and got it to work fine. However, I did get a 422 when I specified a different token query parameter. Being that the status line is missing a phrase, I would assume that the Ruby application is generating it.
I managed to solve the problem. I was passing the parameter so wrong. According to this post [blog]:How to add parameters to a HTTP GET request in Android? "link". This method is used to that I kind of POST request
this method is correct
public void testConverteArquivoJsonEmObjetoJava() {
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("token","0V1AYFK12SeCZHYgXbNMew==$="));
String paramString = URLEncodedUtils.format(params, "utf-8");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(
"http://safep.com/crimes/mobilelist" + "?"
+ paramString);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(get);
String jsonDeResposta = EntityUtils.toString(httpResponse
.getEntity());
System.out.println();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}`

apache http client

Ok... in my quest for surfing the web programmatically in android. I am finally convinced that apache http api is the way to go. I need some help using it though. I have managed to login using httppost however I would like to be able to continue after that. taking the facebook example again, I login to facebook, now I want to use this login session to lets say post a status, how do I proceed?
this is the code so far(requires cleaning and stuff, it was mostly copied from various sources)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("https://www.facebook.com/");
try{
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
// System.out.println("Login form get: " + response.getStatusLine());
// EntityUtils.consume(entity);
// System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
// https://www.facebook.com/login.php?login_attempt=1
HttpPost httpost = new HttpPost("https://www.facebook.com/login.php?login_attempt=1");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email", "****"));
nvps.add(new BasicNameValuePair("pass", "****"));
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
response = httpclient.execute(httpost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entity = response.getEntity();
Toast.makeText(getBaseContext(), "done",Toast.LENGTH_LONG);
System.out.println("Login form get: " + response.getStatusLine());
// EntityUtils.consume(entity);
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
}finally {} }catch (Exception e) {
// TODO: handle exception
}finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
Toast.makeText(getBaseContext(), "done",Toast.LENGTH_LONG);
}
}
}
Replace the stars with your email and password and this gets you inside facebook, how do I proceed from there to post a status?
again please don't tell me there is a facebook api, I don't want to use it, the point here is to learn to use apache libraries
The best way to start would be to wireshark and see what a browser is doing when posting a status. Then adapt to it in the HTTPClient.
The best way to keep a session in Mobile Client should be use OAuth, When you get the OAuth Token, you can use the token to use any api that Facebook providers.

Categories

Resources