You can use my class:
public class HttpHelperConnection {
static String response = "";
//metodo pubblico per ottenere la risposta dal server settando tutti i parametri necessari
/**
*
* @param url
* @param method
* @param post_params
* @param connection_timeout
* @param reading_timeout
* @return
*/
public static String getSyncResponse(String url, String method, HashMap<String, String> post_params,
long connection_timeout, long reading_timeout){
response = "";
response = StartConnection(url, method, post_params, connection_timeout, reading_timeout);
return response;
}
public static String getAsyncResponse(String url, String method, HashMap<String, String> post_params,
long connection_timeout, long reading_timeout){
new Thread(() -> {
response = "";
response = StartConnection(url, method, post_params, connection_timeout, reading_timeout);
}).start();
return response;
}
private static String StartConnection(String url, String method, HashMap<String, String> post_params,
long connection_timeout, long reading_timeout){
String localResponse = "";
try{
URL url_encoded = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url_encoded.openConnection();
conn.setReadTimeout((int)reading_timeout);
conn.setConnectTimeout((int)connection_timeout);
conn.setRequestMethod(method);//il metodo si occupa da solo di inviare la stringa nel metodo richiesto
conn.setDoInput(true);
conn.setDoOutput(true);
conn.addRequestProperty("User-Agent", "Chrome");
conn.setRequestProperty("Accept-Encoding", "identity");
try (OutputStream out_stream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out_stream, "UTF-8"))) {
writer.write(ricevoServerLoginResponse(post_params));
writer.flush();
}catch(IOException e){
System.out.print(e.toString());
}
if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
}else {
localResponse=null;
System.out.println("Error to connect: " + Integer.toString(conn.getResponseCode()));
}
HttpHelperConnection class_conn = new HttpHelperConnection();
String return_code = class_conn.decodeUrlCode(conn.getResponseCode());
if(return_code.equals("OK")){
String line;
InputStreamReader stream_reader = new InputStreamReader(conn.getInputStream());
if (!url_encoded.getHost().equals(conn.getURL().getHost()))
System.out.println("redirectered");//nel caso il browser richiede un'autenticazione
BufferedReader br=new BufferedReader(stream_reader);
while ((line=br.readLine()) != null) {
localResponse+=line;
}
}else
localResponse = "error: " + return_code;
}catch(IOException e){
System.out.print(e.toString());
}
return localResponse;
}
//metodo privato per creare la stringa per i dati passati in post
private static String ricevoServerLoginResponse(HashMap<String, String> params)
throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){//passo ogni dato interno all'hash map
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();
}
private String decodeUrlCode(int res_code){
switch(res_code){
case HttpsURLConnection.HTTP_OK :
return "OK";
case HttpsURLConnection.HTTP_ACCEPTED :
return "HTTP_ACCEPTED";
case HttpsURLConnection.HTTP_BAD_GATEWAY :
return "HTTP_BAD_GATEWAY";
case HttpsURLConnection.HTTP_BAD_METHOD :
return "HTTP_BAD_METHOD";
case HttpsURLConnection.HTTP_BAD_REQUEST :
return "HTTP_BAD_REQUEST";
case HttpsURLConnection.HTTP_CLIENT_TIMEOUT :
return "HTTP_CLIENT_TIMEOUT";
case HttpsURLConnection.HTTP_CONFLICT :
return "HTTP_CONFLICT";
case HttpsURLConnection.HTTP_CREATED :
return "HTTP_CREATED";
case HttpsURLConnection.HTTP_ENTITY_TOO_LARGE :
return "HTTP_ENTITY_TOO_LARGE";
case HttpsURLConnection.HTTP_FORBIDDEN :
return "HTTP_FORBIDDEN";
case HttpsURLConnection.HTTP_GATEWAY_TIMEOUT :
return "HTTP_GATEWAY_TIMEOUT";
case HttpsURLConnection.HTTP_GONE :
return "HTTP_GONE";
case HttpsURLConnection.HTTP_INTERNAL_ERROR :
return "HTTP_INTERNAL_ERROR";
case HttpsURLConnection.HTTP_LENGTH_REQUIRED :
return "HTTP_LENGTH_REQUIRED";
case HttpsURLConnection.HTTP_MOVED_PERM :
return "HTTP_MOVED_PERM";
case HttpsURLConnection.HTTP_MOVED_TEMP :
return "HTTP_MOVED_TEMP";
case HttpsURLConnection.HTTP_MULT_CHOICE :
return "HTTP_MULT_CHOICE";
case HttpsURLConnection.HTTP_NOT_ACCEPTABLE :
return "HTTP_NOT_ACCEPTABLE";
case HttpsURLConnection.HTTP_NOT_AUTHORITATIVE :
return "HTTP_NOT_AUTHORITATIVE";
case HttpsURLConnection.HTTP_NOT_FOUND :
return "HTTP_NOT_FOUND";
case HttpsURLConnection.HTTP_NOT_IMPLEMENTED :
return "HTTP_NOT_IMPLEMENTED";
case HttpsURLConnection.HTTP_NOT_MODIFIED :
return "HTTP_NOT_MODIFIED";
case HttpsURLConnection.HTTP_NO_CONTENT :
return "HTTP_NO_CONTENT";
case HttpsURLConnection.HTTP_PARTIAL :
return "HTTP_PARTIAL";
case HttpsURLConnection.HTTP_PAYMENT_REQUIRED :
return "HTTP_PAYMENT_REQUIRED";
case HttpsURLConnection.HTTP_PRECON_FAILED :
return "HTTP_PRECON_FAILED";
case HttpsURLConnection.HTTP_PROXY_AUTH :
System.out.println("HTTP_PROXY_AUTH");
return "HTTP_PROXY_AUTH";
case HttpsURLConnection.HTTP_REQ_TOO_LONG :
return "HTTP_REQ_TOO_LONG";
case HttpsURLConnection.HTTP_RESET :
return "HTTP_RESET";
case HttpsURLConnection.HTTP_SEE_OTHER :
return "HTTP_SEE_OTHER";
case HttpsURLConnection.HTTP_UNAUTHORIZED:
return "HTTP_UNAUTHORIZED";
case HttpsURLConnection.HTTP_UNAVAILABLE :
return "HTTP_UNAVAILABLE";
case HttpsURLConnection.HTTP_UNSUPPORTED_TYPE :
return "HTTP_UNSUPPORTED_TYPE";
case HttpsURLConnection.HTTP_USE_PROXY :
return "HTTP_USE_PROXY";
case HttpsURLConnection.HTTP_VERSION :
return "HTTP_VERSION";
default :
return "UNKNOWN_ERROR";
}
}
}
You can run this from your Activity:
JSONObject jsobj;
String jsonString = jsonobj.toStirng();
HashMap<String, String> postParams = new HashMap<>();
postParams.put("datas", jsonString);
int connectionTimeout = 1000;
int readingTimeout = 1000;
//If you want connection in your thread
String resposne = HttpHelperConnection.getSyncResponse("https://yourUrl", "POST" , postParams, 1000 , 1000);
//If you want the connection in another thread
response = HttpHelperConnection.getAsyncResponse("https://yourUrl", "POST" , postParams, 1000 , 1000);