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"
Related
I have a post request working successfully in Postman, but when I make the same request from my Android app, I get "Internal Server Error". Do you see any difference between these two requests?
Postman
Android App
class MakeRequest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://sample.com/test");
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Authorization", getB64Auth("username", "password"));
try {
JSONObject identity = new JSONObject();
identity.put("type", "number");
identity.put("endpoint", "12345");
JSONObject options = new JSONObject();
options.put("num", "12345");
JSONObject body = new JSONObject();
body.put("identity", identity);
body.put("method", "test");
body.put("options", options);
StringEntity se = new StringEntity(body.toString());
httppost.setEntity(se);
} catch (IOException e) {
Log.d("IOException", e.toString());
} catch (JSONException e) {
Log.d("JSONException", e.toString());
}
try {
ResponseHandler handler = new BasicResponseHandler();
HttpResponse response = httpclient.execute(httppost);
Log.d("HttpResponse", handler.handleResponse(response).toString());
} catch (ClientProtocolException e) {
Log.d("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.d("IOException", e.toString());
}
return null;
}
private String getB64Auth (String key, String secret) {
String source=key+":"+secret;
String ret="Basic "+Base64.encodeToString(source.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP);
return ret;
}
}
Other thoughts/hints:
Authentication is working properly in the java code. I tried with wrong username & password, and I got "Invalid Authorization"
The JSON string is exactly the same as the one in postman. I printed body.toString(), copied and pasted into Postman, and the request worked fine in Postman.
you should change httppost.setHeader("Content-type", "application/json"); to httppost.setHeader("Content-type", "application/form-data"); or httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
this should solve your issue.
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");
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
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
This is the code I have so far.
public void postData(String toPost) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mywebsite.com/dev/reverser.php");
//This is the data to send
String MyName = toPost; //any data to send
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a php application
String reverseString = response;
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
}//end postData()
Can somebody please tell me what is wrong in the following code! I have established that there is a problem in the try catch block only and not anywhere else in the activity. I just do not know what it is or how to correct it.
My PHP code is quite simple. It is something like this -
//code to reverse the string
$reversed = strrev($_POST["action"]);
echo $reversed;
In a comment above you indicated that you are getting a android.os.NetworkOnMainThreadException.
In the most recent versions of Android you are not allowed to do networking on the main thread as it makes the UI unresponsive. Move your code to a different thread using AsyncTask (see the Android developer guide for details) or some other mechanism.
Adding as a seperate answer as the poster requests to do so .
Assumption :
a ) There is a text box that accepts the URL to load
b ) A button which when clicked performs the networking operation on the URL fetched f
Implement a button click listener that calls the following function :
private void URL()
{
String url = txtURL.getText().toString();
new URLTask().execute(new String[] { url });
}
private class URLTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... urls)
{
BufferedReader br = null;
String url = urls[0];
StringBuffer sb = new StringBuffer("");
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(url));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "value of param1"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
String line;
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
}
catch(Exception e)
{
Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
return(sb.toString());
}
protected void onPostExecute(String result)
{
txtContent.setText(result);
}
You need to implement onPostExecute as well . There are other APIS .
Android Async Task Documentation
Try printing out the exception .
Use this code to print out your response . Check the status of the response
HttpResponse response = client.execute(request);
String line;
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
}
catch(Exception e)
{
Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
Tell us the exception . It would be easy to pinpoint your problems then .
EDIT : ANSWER :
You are trying to perform a networking operation on the MAIN thread . This is an illegal thing to do . Create a AsyncTask i.e create a seperate thread to do your networking operations .
Android Details of the exception
Stackoverflow question
I have a Rails server, and I want my Java desktop application & android app to be able to interact with the standard scaffold (new/ edit/ show/ etc) so I can sync data between everything.
I found this (link) which shows the basic idea but not the actual code..
The catch is that the user needs to be logged in with devise, so they only see their data, not mine or yours!
Please help me regarding this.
JSON will better for android apps. Its lightweight than XML.
when you are connecting to a server. each request will be webservice call to the server. you can send the authentication in the header in Base64 encoded form. so each request is parsed in the server and the credentials can be decoded and authenticated before serving the response.
To identify the device you can send the devices IME number. you can have a table to keep track of the devices that log into your server.
check this question for detail
For the base64 authentication in the client side using json. i haven't done with xml.
public static JSONObject SendHttpPost(Context context, JSONObject jsonObjSend) {
mPrefs = AppConfig.getPreferences(context);
String username = mPrefs.getString("UserName","");
String password = mPrefs.getString("Password","");
String host = mPrefs.getString("URL","");
String port = mPrefs.getString("Port","");
String url = "http:\\myapp.com\controller\getuser"
HttpResponse response = null ;
JSONObject jsonObjRecv =null;
try {
String usercredential = Utility.getB64Auth(username, password);
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(url);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Authorization", usercredential);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
//Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
Log.v(null, "resultString "+resultString);
instream.close();
// Transform the String into a JSONObject
if(resultString!=null){
jsonObjRecv = new JSONObject(resultString);
}
// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<jsonobject>\n"+jsonObjRecv.toString()+"\n</jsonobject>");
return jsonObjRecv;
}
} catch(SocketException se){
se.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Edit yes username and password pre set. use a screen like preference screen to set it. can refer json.org for parsing and creating json. yes can create nested jsons.
JSONObject body = new JSONObject();
JSONObject note = new JSONObject();
JSONObject commit = new JSONObject();
note.put("value", test2);
commit.put("create", note);
body.put("note", note);
body.put("commit", commit);