how to send JSON request and get JSON response from server [duplicate] - java

This question already has answers here:
How To Send json Object to the server from my android app
(4 answers)
Closed 3 years ago.
I have a server to which I need to send a request and get a response.
I am using volley and this is what I have done so far
JSONObject request=new JSONObject();
try {
request.put("ticket_id", ticket_id);
request.put("start", start);
request.put("extra", extra);
request.put("care_category", care_category);
request.put("k_means", "10");
request.put("vendor", vendor);
request.put("earlier_enteries", earlier_enteries);
} catch (JSONException e) {
e.printStackTrace();
}
The response would be something like :
{"calculation":5.4444"}
How should I rend my request and or if there is any better way to do so ?

You have to use HTTPs requests (GET and POST). Retrofit and Gson will get it done.
There's a lot of tutorials and examples about it.
See Retrofit Android Example HTTP GET Request

Related

Java Requests with json data [duplicate]

This question already has answers here:
HTTP POST using JSON in Java
(12 answers)
Closed 1 year ago.
I want to make an HTTP request with Java,
but I'm new to Java and have no clue how.
I've had a look at a few tutorials,
but I was unable to understand anything.
I want to send JSON data and also receive JSON data.
In Python it would look like this:
response = json.load(urllib.request.urlopen(urllib.request.Request('http://localhost:8765', requestJson)))
Any help would be much appreciated.
Use the below link for reference
https://www.baeldung.com/java-http-request
You can use rest template also if you're using external library.
ResponseEntity<> response = restTemplate.exchange(
UriComponentsBuilder.fromHttpUrl(baseurl + "jobs").toString(),
HttpMethod.POST,
new HttpEntity<>(body,headers),
<someClass>.class);

Yahoo Currency Converter API [duplicate]

This question already has answers here:
Has Yahoo suddenly today terminated its finance download API?
(4 answers)
Closed 5 years ago.
I've been using the Yahoo Currency Converter all along without issues.
Here is the function code in Java:
public static Float convert(String currencyFrom, String currencyTo) throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://quote.yahoo.com/d/quotes.csv?s=" + currencyFrom + currencyTo + "=X&f=l1&e=.csv");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpGet, responseHandler);
httpclient.getConnectionManager().shutdown();
return Float.parseFloat(responseBody);
}
However, just yesterday I realised it was throwing the following error:
It has come to our attention that this service is being used in
violation of the Yahoo Terms of Service. As such, the service is being
discontinued. For all future markets and equities data research,
please refer to finance.yahoo.com.
Is there some problems with the code I'm using? Or has the service been discontinued permanently. Any alternative suggestion for real time currency conversion?
I can confirm that the service has been discontinued overnight.
https://forums.yahoo.net/t5/Yahoo-Finance-help/http-download-finance-yahoo-com-d-quotes-csv-s-GOOG-amp-f/m-p/387662/highlight/true#M6207
This is the answer from the admin of the community site.
Although discontinued, you could look at an alternative such as http://fixer.io, which would allow you to do something similar via JSON
https://api.fixer.io/latest?base=currencyFrom&symbols=currencyTo

HttpClient is deprecated (android studio, Target=api 22) [duplicate]

This question already has answers here:
Deprecated Java HttpClient - How hard can it be?
(10 answers)
Closed 7 years ago.
In my Android app it says: org.apache.http.client.httpclient is deprecated.
After some research I found out that Android has deprecated it in API 22. I have searched in the forum and tried: "The application has stopped", Searched google: "The application has stopped". So I have no idea what to do. I hope you guys can help me out. Well here is my code:
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.URL.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success");
// Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_LONG).show();
EDIT:
I'm trying to get some data of my Mysql database. Do you know a good tutorial about how this is done?
Please let me know.
Stop using it and use URLConnection instead. It's been 4 years Google recommends this.
http://android-developers.blogspot.be/2011/09/androids-http-clients.html
If you want an external library with a nicer API, you can try OkHttp: http://square.github.io/okhttp/

When should the HttpClient be closed? [duplicate]

This question already has answers here:
What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?
(8 answers)
Closed 2 years ago.
I am building an Android app that will fire multiple HTTP requests (say a request every second) to a server to fetch data. What are the best practices I must follow?
Should I create and close the client after each request, like the following?
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.close();
}
Or should I create a client initially, use it for all requests and then finally close it when I'm done with it?
The idea of closing your HttpClient is about releasing the allocated ressources. Therefore, It depends on how often you plan on firing those HTTP requests.
Keep in mind that firing a request every 10 seconds is considered an eternity ;)

How to parse HTTP 400 response using Jersey Client into a Java Class?

I am using Jersey client to interact with the Facebook Graph API. The Jersey client helps me parse JSON responses into Java classes.
Sometimes Facebook sends a 400 response along with useful information about the reason for the 400 response. For example: {"error":{"message":"Error validating application. Cannot get application info due to a system error.","type":"OAuthException","code":101}}
Jersey simply throws an exception and eats up the useful part of the response :-(
How do I get it to parse the JSON into a Java class with fields corresponding to the useful error information?
You can use ObjectMapper for that purpose. Basically, create an object that will match up with the content in the JSON and use readValue() method of the mapper to turn the JSON response into an object.
this code works:
try {
User user = user_target
.request()
.get(User.class);
System.out.println(user);
} catch (ClientErrorException primary_exception) {
try {
ErrorResponse error_response = primary_exception.getResponse().readEntity(ErrorResponse.class);
System.out.println(error_response);
} catch (ClientErrorException secondary_exception) {
System.err.println("Secondary Exception: " + secondary_exception.getMessage());
throw new ThisAppException("Secondary Exception", secondary_exception);
}
}

Categories

Resources