1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
try {
URL url = new URL(pUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
String query ="";
if(params.length!=0){
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("'firstParam'", (String) params[0])
.appendQueryParameter("'secondParam'", (String) params[1]);
query = builder.build().getEncodedQuery();
}
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
if(!query.equals("")){
writer.write(query);
}
writer.flush();
writer.close();
os.close();
conn.connect();
//traitement du POST au retour de l'appel:
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
}
reader.close();
json = sb.toString();
}else{
Log.i("retour false", ""+response_code );
}
} catch (UnsupportedEncodingException e) {
Log.e("", e.toString());
} catch (MalformedURLException e) {
Log.e("", e.toString());
} catch (IOException e) {
Log.e("", e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
Log.d("dd ", jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e);
} |
Partager