Reputation: 23
My knowledge is very limited in android I am newBi, can anyone tell me how can I get the response and post of JSON that I am getting....If you have suggestion just edit my code and insert a comment , so that I can identify my missing methods. I can't analyse some posted related question , I already do my research but I can't perfect it. Correct me if my code is wrong or incomplete.
public void httpConnection(HashMap<String, String> postDataParams) {
HttpURLConnection httpcon;
String url = "(url here...)";
String result;
try {
httpcon = (HttpURLConnection) ((new URL(url).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Key", "Value");
httpcon.setRequestProperty("action", "get_scoop");
httpcon.setRequestMethod("POST");
httpcon.connect();
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.close();
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(), "UTF-8"));
String line = "";
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
public class CallAPI extends AsyncTask<String, String, String> {
public CallAPI() {
//set context variables if required
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String urlString = params[0]; // URL to call
String resultToDisplay = "";
InputStream in = null;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(10000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (Exception e) {
Log.e("TAG", e.getMessage());
return e.getMessage();
}
try {
resultToDisplay = IOUtils.toString(in, "UTF-8");
//to [convert][1] byte stream to a string
} catch (IOException e) {
e.printStackTrace();
}
return resultToDisplay;
}
@Override
protected void onPostExecute(String result) {
//Update the UI
}
}
Upvotes: 0
Views: 172
Reputation: 11194
Simple example for fetching data via retrofit
:
Note : this api runs in background thread hence do not call this method from any other background thread like asynctask
private void fetchDoctorClinics() {
if (EasyPadhaiUtils.checkInternetConnection(DoctorDashbaord.this)) {
// State Callback
retrofit2.Callback callback = new retrofit2.Callback<ClinicsModel>() {
@Override
public void onResponse(Call<ClinicsModel> call, Response<ClinicsModel> response) {
}
@Override
public void onFailure(Call<ClinicsModel> call, Throwable t) {
}
};
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.DOMAIN_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
// prepare call in Retrofit 2.0
ClinicsInterface clinicsInterface = retrofit.create(ClinicsInterface.class);
Call<ClinicsModel> call = clinicsInterface.getClinics("10");
call.enqueue(callback);
} else {
// Network not available , handle this
}
}
and below is how you create post request via interface :
public interface ClinicsInterface {
@FormUrlEncoded
@POST(Constants.CONTROLLER_API)
Call<ClinicsModel> getClinics(@Field(Constants.APPOINTMENT_DOCTOR_ID) String doctorId);
}
Do update your gradle with below retrofit lib :
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
Upvotes: 1