Skip to content

Instantly share code, notes, and snippets.

@andrebian
Created October 15, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrebian/7ce869d1eb5470144be5 to your computer and use it in GitHub Desktop.
Save andrebian/7ce869d1eb5470144be5 to your computer and use it in GitHub Desktop.
class RequestPost {
public Boolean isJson(String str) {
try {
new JSONObject(str);
} catch (JSONException ex) {
try {
new JSONArray(str);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
public JSONObject sendSomething(String someParam) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", someParam));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
if( isJson(responseBody) ) {
return new JSONObject(responseBody);
} else {
return null;
}
} catch (ClientProtocolException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment