I have rest api designed in Slim 3. which stores the customer details in MySQL db. I am using Retrofit 1.9 to connect to webservice. I am receiving server error 500 where as same request working fine in POSTMAN.
//using retrofit
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(Config.CUSTOMER_URL).build();
RegisterCustomer api = adapter.create(RegisterCustomer.class);
api.registerCustomer(custName.toString(),
phoneNumber.toString(),
address.toString(),
Config.API_KEY, new Callback<retrofit.client.Response>() {
#Override
public void success(retrofit.client.Response result, retrofit.client.Response response) {
BufferedReader reader = null;
String output = "";
try {
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("customer result",result.getBody()+"##"+result.getStatus() +"##" +response.getBody().toString());
}
#Override
public void failure(RetrofitError error) {
Log.d("customer save fail ",error.getMessage());
}
});
Interface:
public interface RegisterCustomer
{
#FormUrlEncoded
#POST("/customer")
public void registerCustomer(
#Field("cust_name") String cust_name,
#Field("phone") String phone,
#Field("address") String address,
#Field("apikey") String apikey,
Callback<Response> callback);
}
My php code.
// Adding customer
// pass cust_name,phone,address and apikey
$app->post('/customer', function ($request, $response, $args) {
$_message = $request->getParsedBody();
$customer = new Customer();
$customer->cust_name = $_message['cust_name'];
$customer->phone = $_message['phone'];
$customer->address = $_message['address'];
$customer->apikey = $_message['apikey'];
$payload=[];
$customer->save();
if ($customer->id) {
$payload = ['cust_id' => $customer->id,
'cust_uri' => '/customer/' . $customer->id
];
return $response->withStatus(201)->withJson($payload);
}else {
return $response->withStatus(400);
}
});
Related
I want to wait for the completion of a sub-thread to determine the login status. But I'm not familiar with how to write internal classes, so I'd like to ask how to write code to wait for a child thread to finish execution in the login function.
public class LoginDataSource {
static LoggedInUser loggedUser = new LoggedInUser();
public Result<LoggedInUser> login(String username, String password) {
try {
// TODO: handle loggedInUser authentication
loginMyBlog(username, password, loggedUser);
if (loggedUser.isLogStatue()) {
return new Result.Success<>(loggedUser);
} else {
return new Result.Failed("pass incorrect");
}
} catch (Exception e) {
return new Result.Error(new IOException("Error logging in", e));
}
}
public void logout() {
// TODO: revoke authentication
}
private void loginMyBlog(String usernames, String passwords, LoggedInUser userAuth) {
new Thread(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
// Code for sending network requests
//...
//Code to determine if the login is successful
try {
Response response = client.newCall(request).execute();
final String responseData = response.body().string();
JSONObject jsonObject = JSONObject
.parseObject(responseData);
String code = jsonObject.getString("code");
if (code.equals("20000")){
// login success
JSONObject dataObject = JSONObject.parseObject(jsonObject.getString("data"));
userAuth.setId(dataObject.getInteger("id"));
userAuth.setIntro(dataObject.getString("intro"));
userAuth.setLogStatue(true);
Log.d("test", "登录成功"+userAuth);
}else if (code.equals("51000")){
// login failed
userAuth.setLogStatue(false);
}
} catch (IOException e) {
e.printStackTrace();
// network err
}
}
}).start();
}
}
Thanks.
I'm trying to get the value for the key 'GBP' in the following link: https://api.fixer.io/latest
I've managed to connect to the API successfully and I'm able to cycle through the keys until I get "rates". Inside rates though, I don't know how I cycle through all the currencies until I find 'GBP'.
Note: I'm paring the Json - I'm struggling to parse a Json object that has a Json within it. It's different to the duplicates you've referenced.
My code so far looks like this:
String urlStr = "https://api.fixer.io/latest";
AsyncTask.execute(new Runnable() {
#Override
public void run() {
// Create URL
URL url = null;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// Create connection
try {
HttpURLConnection myConnection =
(HttpURLConnection) url.openConnection();
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginObject(); // Start processing the JSON object
while (jsonReader.hasNext()) { // Loop through all keys
String key = jsonReader.nextName(); // Fetch the next key
if (key.equals("rates")) { // Check if desired key
// Fetch the value as a String
String value = jsonReader.nextString();
//currentCurrency = value;
break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
}
} else {
// Error handling code goes here
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
Try this
JSONObject jsonObject = new JSONObject(" your json response ");
Iterator iteratorObj = jsonObject.keys();
while (iteratorObj.hasNext())
{
String JsonObjRates = (String)iteratorObj.next();
if (JsonObjRates.equals("rates")) {
JSONObject jo_rates = jsonObject.getJSONObject(JsonObjRates);
Iterator<String> keys = jo_rates.keys();
while (keys.hasNext())
{
String key = keys.next();
String value = jo_rates.getString(key);
Log.i("RATES key", key);
Log.i("RATES value", value);
if(key.equals("GBP"))
{
Log.i("GBP RATES key", key);
Log.i("GBP RATES value", value);
}
}
}
}
Output
Instead of Using manual parsing used below things.
Please Use RoboPojo Generator into Android Studio it will helps you to create model class for you and directly setData to your model class.
if you are using Gson to setData.
Below ilink is helping to you :
https://github.com/robohorse/RoboPOJOGenerator
hope this helps you.
You can use Volleylibrary to make request that url and you will take response.
after take response via related url, you can parse it on Android Studio.
dependencies {
...
compile 'com.android.volley:volley:1.1.0'
}
above will be added in dependencies.
below will be added in your Activity(like MainActivity).
String url ="https://api.fixer.io/latest";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject resultJSON=new JSONObject(response);
JSONObject rates=resultJSON.getJSONObject("rates");
string GPB=rates.getString("GPB");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
I guess it will work. make feedback whether it works or not.
Try this.
You have to loop through jsonobject so first create class for rates.
public Rates readRates(JsonReader reader) throws IOException {
String country_rate = null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("GBP")) {
country_rate = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
return new Rates(country_rate);
}
Decalre your class at start of this http method
Rates rate = null;
Replace this Code
if (key.equals("rates")) { // Check if desired key
// Fetch the value as a String
String value = jsonReader.nextString();
//currentCurrency = value;
break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
With this
if (key.equals("rates"))
{
rate = readRates(jsonReader);
String rate_value = rate.country_rate;
}
else
{
jsonReader.skipValue(); // Skip values of other keys
}
For more details https://developer.android.com/reference/android/util/JsonReader.html
Hope it helps.!
string apiUrl1 = string.Format(#"http://xxx.xxx.x.xxx/test/Home/getdata?id=1");
public static string GetData(string url)
{
string Result = "";
try
{
using (WebClient client = new WebClient())
{
Result = client.DownloadString(string.Format(#"" + url + ""));
}
}
catch (Exception e)
{
string msg = e.Message;
Result = "";
}
return Result;
}
I am trying to get Data from my Published .Net MVC Web Project But i am getting Server Error "The remote server returned an error: (500) Internal Server Error."
My MVC Controller Code is Here
public JsonResult getdata(int? id)
{
List<Items> dbItems = Items.getItemsData(id);
return Json(dbItems, JsonRequestBehavior.AllowGet);
}
Besides the fact that you would probably be better suited using ASP.NET Web API (you wouldn't have to specifically convert your response to JSON on your controller), you can try something like below. As far as the server error, you would have to debug that server side.
public class RestClient
{
HttpClient client;
private string RestUrl = "http://192.168.1.103/test/Home/";
private static List<Items> _items = new List<Items>();
public RestClient()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 9999999;
}
public async Task<List<Item>> GetItems(int? id)
{
List<Item> items= new List<Item>();
var uri = new Uri(RestUrl + "getdata?id=" + id);
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
items= JsonConvert.DeserializeObject<List<Item>>(content);
_items.AddRange(items);
}
else
{
//do something
}
return _items;
}
}
what is the sample code for OAuth 1.0a(one leg) authentication in android?
is there a library for it? .
I use eclipse and i'm new in android. can anyone clarify the path for me?
to answer my own question:
download Scrib.jar library and add it to your lib folder(you can download it from (here)
create a class with name "OneLeggedApi10" and copy below code in it:
import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.Verb;
import org.scribe.model.Token;
public class OneLeggedApi10 extends DefaultApi10a {
#Override
public String getAccessTokenEndpoint() {
return null;
}
#Override
public String getRequestTokenEndpoint() {
return null;
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return null;
}
#Override
public Verb getAccessTokenVerb() {
return Verb.GET;
}
#Override
public Verb getRequestTokenVerb() {
return Verb.GET;
}
}
now you can do OAuth authentication:
String RESOURCE_URL = "http://yourDomain.com/wc-api/v3/orders";
String SCOPE = "*"; //all permissions
Response response;
OAuthRequest request;
String responsebody = "";
OAuthService service = new ServiceBuilder().provider(OneLeggedApi10.class)
.apiKey("your_key")
.apiSecret("your_apiSecret")
.signatureType(SignatureType.QueryString)
.debug()
/*.scope(SCOPE).*/
.build();
request = new OAuthRequest(Verb.GET, RESOURCE_URL);
service.signRequest(new Token("", ""), request);
// Now let's go and ask for a protected resource!
Log.d("scribe","Now we're going to access a protected resource...");
try{
response = request.send();
if (response.isSuccessful()) {
responsebody = response.getBody();
}
} catch (Exception e) {
e.printStackTrace();
}
note that if you are not using above code in an AsyncTask,then put the request.send() part in a thread (actually whole try_catch section) for avoiding run in main thread exception
finally if you want to send data,for example in a case that you want to update an order,replace
request = new OAuthRequest(Verb.GET, RESOURCE_URL);
with these lines:
String payload = yourJsonOBJ.toString();
request = new OAuthRequest(Verb.PUT, RESOURCE_URL);
request.addHeader("Content-Type", "application/json");
request.addPayload(payload);
more information in WooCommerce Documentation site
Hope it help ;)
good luck..
new Thread() {
#Override
public void run() {
String RESOURCE_URL = "http://www.woocommerce.com/wp-json/wc/v1/api/";
String SCOPE = "*"; //all permissions
Response response;
OAuthRequest request;
String responsebody = "";
OAuthService service = new ServiceBuilder().provider(OneLeggedApi10.class)
.apiKey("yourConsumerKey")
.apiSecret("yourConsumerSecret")
.signatureType(SignatureType.QueryString)
.debug()
/*.scope(SCOPE).*/
.build();
request = new OAuthRequest(Verb.GET, RESOURCE_URL);
service.signRequest(new Token("", ""), request);
// Now let's go and ask for a protected resource!
Log.d("scribe","Now we're going to access a protected resource...");
try {
response = request.send();
if (response.isSuccessful()) {
responsebody = response.getBody();
Log.v("response", responsebody);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
This code is updated from above, the above code is working getting JSON from wordpress Woocommerce API.
But if you wondering how to use Thread this is the answer.
And I add Log.v for see the json response.
I am trying to parse twitter/trends/place api to my android app with retrofit, however, i have been able to parse the api below with retrofit and i get all my desired data:
https://api.twitter.com/1.1/search/tweets.json,
am using the same approach for https://api.twitter.com/1.1/trends/place.json, but i am getting this exception
GSON throwing “Expected BEGIN_OBJECT but was BEGIN_ARRAY
Below is my code. i believe my error is coming from one of the code below, some should please help me.
TwitterApiService.java
public interface TwitterApiService {
#GET(ApiConstants.TWITTER_TREND_SEARCH_CODE )
void getTweetTagList(
#Header("Authorization") String authorization,
#Query("id") String id,
Callback<TweetTagList> callback
);
#FormUrlEncoded
#POST("/oauth2/token")
void getToken(
#Header("Authorization") String authorization,
#Field("grant_type") String grantType,
Callback<TwitterTokenType> response
);
}
TwitterServiceProvider.java
public class TwitterServiceProvider {
private static final String TAG = TwitterServiceProvider.class.getName();
private TwitterApiService mApi;
private Bus mBus;
public TwitterServiceProvider(TwitterApiService api, Bus bus) {
this.mApi = api;
this.mBus = bus;
}
#Subscribe
public void onLoadTweets(final SearchTweetsTagEvent event) {
mApi.getTweetTagList("Bearer " + event.twitterToken, event.id, new Callback<TweetTagList>() {
#Override
public void success(TweetTagList response, Response rawResponse) {
mBus.post(new SearchTweetsTagEventOk(response));
}
#Override
public void failure(RetrofitError error) {
Log.e(TAG, error.toString(), error);
mBus.post(new SearchTweetsEventFailed());
}
});
}
#Subscribe
public void onGetToken(TwitterGetTokenEvent event) {
try {
mApi.getToken("Basic " + getBase64String(ApiConstants.BEARER_TOKEN_CREDENTIALS), "client_credentials", new Callback<TwitterTokenType>() {
#Override
public void success(TwitterTokenType token, Response response) {
PrefsController.setAccessToken(TwitterSearchApplication.getAppContext(), token.accessToken);
PrefsController.setTokenType(TwitterSearchApplication.getAppContext(), token.tokenType);
mBus.post(new TwitterGetTokenEventOk());
}
#Override
public void failure(RetrofitError error) {
Log.e(TAG, error.toString(), error);
mBus.post(new TwitterGetTokenEventFailed());
}
});
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.toString(), e);
}
}
/*private static String getResponseBody(InputStream inputStream) {
StringBuilder sb = new StringBuilder();
BufferedReader bReader = null;
try {
bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
} catch (UnsupportedEncodingException ex) {
Log.e("LOG", "", ex);
} catch (ClientProtocolException ex1) {
Log.e("LOG", "", ex1);
} catch (IOException ex2) {
Log.e("LOG", "", ex2);
}
return sb.toString();
}*/
/*// converts a string of JSON data into a Twitter object
private static TweetList jsonToTweetLost(String result) {
TweetList twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, TweetList.class);
} catch (IllegalStateException ex) {
Log.e("LOG", "",ex);
}
}
return twits;
}*/
}
Tweet.java
public class Tweet {
#SerializedName("created_at")
public String dateCreated;
#SerializedName("trends")
public TweetTag trend;
#Override
public String toString(){
return trend.nameTag;
}
}
TweetTagList.java
public class TweetList {
#SerializedName("")
public ArrayList<Tweet> tweets;
}
SearchTweetsTagEvent.java
public class SearchTweetsTagEvent {
public final String id;
public final String twitterToken;
public SearchTweetsTagEvent(String twitterToken, String hashtag) {
this.id = hashtag;
this.twitterToken = twitterToken;
}
}
Looks like you are using wrong model object for JSON response parsing. You can choose the proper one from twitter-kit-android. If I understand correctly Place.java is what you are looking for.