I´m looking for a solution to implement a JSON-POST request with OKHTTP. I´ve got an HTTP-Client.java file which handles all the methods (POST, GET, PUT, DELETE) and in the RegisterActivity I´d like to POST the user-data (from the input fields) JSON-formatted to the server.
This is my HTTP-Client.java
public class HttpClient{
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
public static OkHttpClient client = new OkHttpClient.Builder()
.cookieJar(new CookieJar() {
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
#Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(), cookies);
}
#Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
})
.build();
public static Call post(String url, String json, Callback callback) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body.create(JSON, json))
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
}
... and this is the onClick-Part from the RegisterActivity
btnRegRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO
String registerData = "{\"email\":\"" + etRegisterEmail.getText().toString() + "\",\"password\":\"" + etRegisterPasswort.getText().toString() + "\"}";
try {
HttpClient.post(ABSOLUTE_URL, registerData, new Callback(){
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String resp = response.body().string();
if (resp != null) {
Log.d("Statuscode", String.valueOf(response.code()));
Log.d("Body", response.body().string());
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
Everytime I start the app it crashes when I click the Register-Button caused by a FATAL EXPECTION 'android.os.NetworkOnMainThreadException'
I´ve alread read something about the AsyncTask but I don´t know exactly how to do this.
Try my code below
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
Map<String, String> params = new HashMap<String, String>();
params.put("msisdn", "123123");
params.put("name", "your name");
JSONObject parameter = new JSONObject(param);
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, parameter.toString());
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("content-type", "application/json; charset=utf-8")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e("response", call.request().body().toString());
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.e("response", response.body().string());
}
});
It's because you are trying to execute the HTTP query on the main thread (or UI thread). You shouldn't do a long task on the main thread because your app will hang, because the drawing routines are executed in that thread (hence his another name "UI Thread"). You should use another thread to make your request. For example:
new Thread(){
//Call your post method here.
}.start();
The Android asynctask is a simple class to do asynchronous work. It executes first his "onPreExecute" method on the calling thread, then his "doInBackground" method on a background thread, then his "onPostExecute" method back in the calling thread.
Try using Retrofit library for making Post request to the server. This provides a fast and reliable connection to the server.
You can also use Volley library for the same.
Related
I use OkHttp for requests to my raspberry. I am thinking about putting the requests in a separate class.
Currently I have one method to send requests. The code is as follows:
private void sendRequest(String url, JSONObject json) {
Log.d(TAG, "sendRequest: Das Json: " + json);
// Authentication for the request to raspberry
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.authenticator(new Authenticator() {
#Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic("username", "password");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
});
// Sending out the request to the raspberry
OkHttpClient okHttpClient = client.build();
RequestBody body = RequestBody.create(null, new byte[]{});
if( json != null) {
body = RequestBody.create(MediaType.parse(
"application/json"),
json.toString()
);
}
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.d(LOG, "Big Fail");
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
ResponseBody responseBody = response.body();
if( !response.isSuccessful() ) {
Log.d(TAG, "onResponse: We are in !response.successful()");
throw new IOException("Response not successful: " + response );
}
Log.d(LOG, "onResponse: Response is: " + responseBody.string());
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG, "onResponse: failed!" + e);
}
}
});
}
Here is an example how the sendRequest() function is called:
private void makePremixCall(Premix premix) {
JSONArray jsonArray = new JSONArray();
ArrayList<Premixable> usedPremixables = premix.getUsedPremixables();
for(Premixable usedPremixable: usedPremixables) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Silo", usedPremixable.getmSilo());
jsonObject.put("Gramm", usedPremixable.getmKgPerCow() * mFeeding.getmNumberOfCows());
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Components", jsonArray);
sendRequest("http://192.168.178.49:5000/evaluatePost", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "makePremixCall: " + e);
}
}
My problem with this: I would like to have a separate class, which offers the function makePremix(Premix premix) and other functions that I need.
The only solution that comes to my mind is implementing the requests synchronously in the separate class and call that separate class in an AsyncTask in the class I am working in.
Do I oversee something? Is there a way to create a separate class and still use the OkHttp enqueue method?
You could extract makePremix(Premix premix) in a separate class and make sendRequest() public (or maybe package-private depending on your use case).
public void sendRequest(String url, JSONObject json)
However since sendRequest is generic and can be used by any other makeAnotherCall() in some other class you would need to get back result of every requests. Hence you can extract the Callback out of sendRequest()
public void sendRequest(String url, JSONObject json, Callback callback)
Now your sendRequest will look like
private void sendRequest(String url, JSONObject json) {
Log.d(TAG, "sendRequest: Das Json: " + json);
// Authentication for the request to raspberry
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.authenticator(new Authenticator() {
#Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic("username", "password");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
});
// Sending out the request to the raspberry
OkHttpClient okHttpClient = client.build();
RequestBody body = RequestBody.create(null, new byte[]{});
if( json != null) {
body = RequestBody.create(MediaType.parse(
"application/json"),
json.toString()
);
}
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
okHttpClient.newCall(request).enqueue(callback);
}
Hope it makes sense!
Also as a side note, see that you are creating a new OkHttp Client every time you call sendRequest. You could probably optimise memory here by caching the client and reusing it.
This is my code to get the JSON string from my PHP server.
When I run this the app crashes and says that there is an error with Response response = client.newCall(request).execute();
What am I doing wrong?
public class MainActivity extends Activity {
//private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<Void, Void, String>(){
#Override
protected String doInBackground(Void... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try {
Response response = client.newCall(request).execute();
Log.d("OkHttp", "doInBackground() called with: " + "params = [" + response.body().string() + "]");
return response.body().string();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
}
You don't need to put this into an async task as you can use the call back of the OKHttp library which itself is async.
Second thing is you are using the wrong method. Instead of execute() you should use enqueue() which has a callback as a parameter as I mentioned above.
Try this code:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// Observe reason of failure using
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
// Use response here
}
else{
// Observe error
}
}
});
I'm using the GettyImages API: http://developers.gettyimages.com/api/docs/v3/search/images/get/
I'm getting Account Inactive as the response.In the Dashboard my Status is Active
Can't figure out what's wrong
Here's the code:
String mySearch = "football";
HashMap<String, String> header = new HashMap<String, String>();
header.put("API_KEY", API_KEY);
String url = "https://api.gettyimages.com/v3/search/images?phrase=football";
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.header("API_KEY", API_KEY)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
alertUserAboutError();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.v("Response: ", jsonData);
}
catch (IOException e)
{
e.printStackTrace();
Log.d("Exception Caught: ",e.toString());
}
}
});
If your API Key is correct,
then you're missing request Authorization header.
See the Getty github project for reference:
https://github.com/gettyimages/gettyimages-api_java
When I'm working on networking functions in OkHttp, there are mainly 2 patterns I come across with:
Listener pattern
Callback pattern
Listener Pattern example:
// Listener class
public interface NetworkListener {
void onFailure(Request request, IOException e);
void onResponse(Response response);
}
// NetworkManager class
public class NetworkManager {
static String TAG = "NetworkManager";
public NetworkListener listener;
OkHttpClient client = new OkHttpClient();
public void setListener(NetworkListener listener) {
this.listener = listener;
}
void post(String url, JSONObject json) throws IOException {
//RequestBody body = RequestBody.create(JSON, json);
try {
JSONArray array = json.getJSONArray("d");
RequestBody body = new FormEncodingBuilder()
.add("m", json.getString("m"))
.add("d", array.toString())
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
// Asynchronous Mode
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.e(TAG, e.toString());
if(listener != null) {
listener.onFailure(request, e);
}
}
#Override
public void onResponse(Response response) throws IOException {
Log.w(TAG, response.body().string());
if(listener != null) {
listener.onResponse(response);
}
}
});
} catch (JSONException jsone) {
Log.e(TAG, jsone.getMessage());
}
}
}
// In the Activity
NetworkManager manager = new NetworkManager();
manager.setListener(this);
try {
requestState = RequestState.REQUESTING;
manager.post("http://www.example.com/api.php", reqObj);
} catch(IOException ioe) {
Log.e(TAG, ioe.getMessage());
}
Callback Pattern example:
// in onCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
doGET(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.d("OkHttp", "Shit happens");
}
#Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
String strResponse = response.body().string();
Gson gson = new Gson();
Wrapper wrapper = gson.fromJson(strResponse, Wrapper.class);
Log.d("OkHttp", wrapper.getListContents());
} else {
Log.d("OkHttp", "Request not successful");
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
Call doGET(Callback callback) throws IOException {
// Start Network Request
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://www.example.com/api.php").build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
What are the advantages and disadvantages of using the 2 patterns above?
IMHO, they are not different, actually you can find that Callback is also an interface.
package com.squareup.okhttp;
import java.io.IOException;
public interface Callback {
/**
* Called when the request could not be executed due to cancellation, a
* connectivity problem or timeout. Because networks can fail during an
* exchange, it is possible that the remote server accepted the request
* before the failure.
*/
void onFailure(Request request, IOException e);
/**
* Called when the HTTP response was successfully returned by the remote
* server. The callback may proceed to read the response body with {#link
* Response#body}. The response is still live until its response body is
* closed with {#code response.body().close()}. The recipient of the callback
* may even consume the response body on another thread.
*
* <p>Note that transport-layer success (receiving a HTTP response code,
* headers and body) does not necessarily indicate application-layer
* success: {#code response} may still indicate an unhappy HTTP response
* code like 404 or 500.
*/
void onResponse(Response response) throws IOException;
}
However, when I want to reuse some codes (or build an util class), I often use as the following:
Interface:
public interface OkHttpListener {
void onFailure(Request request, IOException e);
void onResponse(Response response) throws IOException;
}
Util class:
public class OkHttpUtils {
public static void getData(String url, final OkHttpListener listener){
OkHttpClient client = new OkHttpClient();
// GET request
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
listener.onFailure(request, e);
}
#Override
public void onResponse(Response response) throws IOException {
listener.onResponse(response);
}
});
}
// the following uses built-in okhttp's Callback interface
public static void getData2(String url, Callback callbackListener){
OkHttpClient client = new OkHttpClient();
// GET request
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(callbackListener);
}
// other methods...
}
Then in activity classes:
OkHttpListener listener = new OkHttpListener() {
#Override
public void onFailure(Request request, IOException e) {
Log.e(LOG_TAG, e.toString());
}
#Override
public void onResponse(Response response) throws IOException {
String responseBody = response.body().string();
Log.i(LOG_TAG, responseBody);
}
};
String url = "http://myserver/api/getvalues";
OkHttpUtils.getData(url, listener);
String url1 = "http://myserver/api/getvalues/123";
OkHttpUtils.getData(url1, listener);
or
Callback callbackListener = new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.e(LOG_TAG, e.toString());
}
#Override
public void onResponse(Response response) throws IOException {
String responseBody = response.body().string();
Log.i(LOG_TAG, responseBody);
}
};
String url = "http://myserver/api/getvalues";
OkHttpUtils.getData2(url, callbackListener);
String url1 = "http://myserver/api/getvalues/123";
OkHttpUtils.getData2(url1, callbackListener);
Hope it helps!
I am using an asynchronous Okhttp to do request and then use the response to fill in the UI.
My idea was to wait in the main thread for the response and then start a new activity. Is this the best way? If so, how can I wait and access the parsed data of the response in the main thread?
Main activity:
public void sendMessage(View view) throws IOException, InterruptedException {
Intent intent = new Intent(this, DisplayMessageActivity.class);
...
HttpHelper client = new HttpHelper();
String response = client.get("https://www.google.com");
...
intent.putExtra(EXTRA_MESSAGE, message+"\nresponse:\n"+response);
Bundle b = new Bundle();
b.putStringArray("DATA_GET", client.dataOut);
intent.putExtras(b);
startActivity(intent);
}
HttpHelper class:
public class HttpHelper {
OkHttpClient client = new OkHttpClient();
String[] dataOut;
String get(String url) throws IOException, InterruptedException {
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override public void onFailure(Request request, IOException e) {
e.printStackTrace();
}
#Override public void onResponse(Response response) throws IOException{
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// parsing response
dataOut = ...;
}
});
return "done";
}
}
Thanks,
No it is a bad way. I recommend using Retrofit, it will handle most of the boilerplate networking stuff for you on a background thread and will serve you the response via a callback when it completes.