Home > database >  How return a String Response from OkHttpClient in a Method
How return a String Response from OkHttpClient in a Method

Time:12-26

I'm trying to get the response from method but I can't access it in return. Someone can help me?

this is my code

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class Teste {

    private final OkHttpClient client = new OkHttpClient();

    private String response = null;

    public void setResponse(String response){
        this.response = response;
    }

    public String getResponse(){
        return this.response;
    }

    public void Request(String url, FormBody formBody) throws Exception {

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                setResponse(e.getMessage());
            }

            @Override public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (!response.isSuccessful()) throw new IOException("Unexpected code "   response);

                    setResponse(responseBody.string());
                }
            }
        });
    }
}

And I call it in MainActivity

Teste teste = new Teste();

teste.Request("http://127.0.0.1/teste.php", new FormBody.Builder()
        .add("fname", "teste")
        .build());

Toast.makeText(this, teste.getResponse(), Toast.LENGTH_SHORT).show();

I tried created get and set methods inside the class to try to get the return...

CodePudding user response:

The problem here is that enqueue(...) will make the request asynchronously, and you are trying to get the response immediately before the request has completed. You could try showing the toast at the onResponse-callback, so it will be shown when the request has completed. You need to show the toast in the main thread and onResponse is not called from the main thread. You need to do this to show it from the main thread:

Handler handler = new Handler(Looper.getMainLooper());

handler.post(new Runnable() {

    @Override
    public void run() {
        // Show the toast here
    }
});

CodePudding user response:

Will I use Retrofit and volley normally. but if you want to return String Response then you can try below code.

public static String GetServerDetail(String Query) throws IllegalStateException,IOException, JSONException 
{
    String result = null;
    InputStream ies = null;
    // Creating Http Object..
    myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    DefaultHttpClient httpclient = new DefaultHttpClient(myParams);
    HttpPost httppost = new HttpPost(GlobleMethods.setting.getUrl());
    ArrayList<NameValuePair> namevaluepair = new ArrayList<NameValuePair>();
    // parameter
    namevaluepair.add(new BasicNameValuePair("ServerName",=""));
    namevaluepair.add(new BasicNameValuePair("DBName", ""));
    namevaluepair.add(new BasicNameValuePair("UID",""));
    namevaluepair.add(new BasicNameValuePair("Query_Type", Query));
    httppost.setEntity(new UrlEncodedFormEntity(namevaluepair));

    HttpResponse httpresponse = httpclient.execute(httppost);

    HttpEntity entity = httpresponse.getEntity();
    ies = entity.getContent();
    // converting in to string
    BufferedReader br = new BufferedReader(new InputStreamReader(ies,
            "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = br.readLine()) != null) {
        sb.append(line   "\n");
    }
    ies.close();
    result = sb.toString();
    return result;
}
  • Related