How to send sms using Twilio Api in Android - java

How to send sms using Twillio Api in Android.
Here is my code.
What I don't know is how to set http request body.
When I test it using CocoaRestClient(a tool for api test), it is working well.
Help me please.
public void sendInviteSMS(String kToNumber) {
int random4Num = generateRequestCode();
...
String kTwilioSID = "...";
String kTwilioSecret = "...";
String kFromNumber = "...";
String message = String.format("%s has sent you a invite. To accept, enter the following code: %d.", AppUtil.sharedObject().userFirstName, random4Num);
String kMessage = message;
String urlString = String.format("https://%s:%s#api.twilio.com/2010-04-01/Accounts/%s/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID);
HashMap postData = new HashMap();
postData.put("From", kFromNumber);
postData.put("To", kToNumber);
postData.put("Body", kMessage);
// Validate user with the POST call
AsyncTask doPost = new TwilioPost(urlString) {
#Override
protected void onPostExecute(String result) {
Log.v("PHONE", result);
}
}.execute(postData);
}
...
public class TwilioPost extends AsyncTask<HashMap<String, String>, Void, String> {
private String remoteURL;
private static final String TAG = "Wayjer";
public TwilioPost(String remoteURL) {
this.remoteURL = remoteURL;
}
////////////////////////////////////////////
// Call "doPost" in the background thread
///////////////////////////////////////////
#Override
protected String doInBackground(HashMap<String, String>... hashMaps) {
try {
return doPost(hashMaps[0]);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
///////////////////////////////////////////////////////
// Override to convert result string to a JSONObject
//////////////////////////////////////////////////////
#Override
protected void onPostExecute(String result) {
try {
Log.v(TAG, result);
} catch (Exception e) {
Log.v(TAG, e.toString());
}
}
public String doPost(HashMap<String, String> postData) throws IOException {
URL url = new URL(remoteURL);
String response = "";
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
String postString = buildString(postData);
byte[] postBytes = postString.getBytes("UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
// Write parameter...
OutputStream outStream = connection.getOutputStream();
outStream.write(postBytes);
outStream.flush();
outStream.close();
connection.connect();
int resCode = connection.getResponseCode();
Log.v(TAG, "Response Message: " + connection.getResponseMessage());
if (resCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
response += line;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String buildString(HashMap<String, String> postData) throws UnsupportedEncodingException {
StringBuilder strBuilder = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : postData.entrySet()) {
try {
Log.v(TAG, "HTTPPOST ENTRY: " + entry.getKey() + " - " + entry.getValue());
if (first)
first = false;
else
strBuilder.append("&");
strBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
strBuilder.append("=");
strBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch (Exception e) {
}
}
return strBuilder.toString();
}
}

Megan from Twilio here.
Interacting with the Twilio REST API directly from your mobile app is not recommended.
When sending SMS from Android, I would suggest that you have a server component using your language of choice. This allows you to keep your API credentials a secret.
Your mobile app would then connect to your server to make the request for sending SMS via the REST API with the parameters of the From, To and Body of the message:
https://www.twilio.com/docs/api/rest/sending-messages
In Java:
// You may want to be more specific in your imports
import java.util.*;
import com.twilio.sdk.*;
import com.twilio.sdk.resource.factory.*;
import com.twilio.sdk.resource.instance.*;
import com.twilio.sdk.resource.list.*;
public class TwilioTest {
// Find your Account Sid and Token at twilio.com/user/account
public static final String ACCOUNT_SID = "YOUR_ACCOUNT_SID";
public static final String AUTH_TOKEN = "[AuthToken]";
public static void main(String[]args) throws TwilioRestException {
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
// Build the parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("To", "+16518675309"));
params.add(new BasicNameValuePair("From", "+14158141829"));
params.add(new BasicNameValuePair("Body", "Hey Jenny! Good luck on the bar exam!"));
params.add(new BasicNameValuePair("MediaUrl", "http://farm2.static.flickr.com/1075/1404618563_3ed9a44a3a.jpg"));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
Message message = messageFactory.create(params);
System.out.println(message.getSid());
}
}
Please let me know if this helps!
If you can otherwise provide an example error message you may be receiving with your code, I can take a closer look.

Related

How do I get the Value out of my Class into my TextViewField

At the moment I am trying to make an Android App with Android Studio with GET and POST data into/from an API.
My problem at the moment is that I want to have the response of the POST request displayed in my app. For this I made the TextView TW_Rueckgabe. I also made another Method just for this so it can Display the Request which is
public String returnString() {
return fetching_data;
}
but the response is not saved in TW_Rueckgabe.
MainActivity.java
final TextView[] TW_Rueckgabe = {findViewById(R.id.textViewRueckgabe)};
Button sendBtn = findViewById(R.id.sendBtn);
sendBtn.setOnClickListener(v -> {
String POST_url = "http://dphost.ddns.net:1573/cool/post.php";
String requestData = "data=" + TW_Benutzername.getText().toString();
POSTRequestTask test = (POSTRequestTask) new POSTRequestTask().execute(POST_url, requestData);
TW_Rueckgabe[0].setText(test.fetching_data);
});
POSTRequestTask Class:
class POSTRequestTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String url = params[0];
String requestData = params[1];
String response = "";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setDoOutput(true);
// add request data
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(requestData);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer responseBuffer = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseBuffer.append(inputLine);
}
in.close();
response = responseBuffer.toString();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// print result
System.out.println("\n\n\n" + result + "\n\n\n");
fetching_data = result;
}
public String returnString() {
return fetching_data;
}
}
I tried to make a new Object and then save the Variable from the Object, didn't work.
interface Callback {
void onResponse(String response);
}
MainActivity {
private Callback callback = new Callback() {
#Override
void onResponse(String response) {
TW_Rueckgabe[0].setText(test.fetching_data);
}
}
sendBtn.setOnClickListener(v -> {
String POST_url = "http://dphost.ddns.net:1573/cool/post.php";
String requestData = "data=" + TW_Benutzername.getText().toString();
POSTRequestTask test = new POSTRequestTask(callback).execute(POST_url, requestData);
});
}
class POSTRequestTask(Callback callback) extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// do your request as you're doing now and return the result
}
#Override
protected void onPostExecute(String result) {
// callback interface method call here
callback.onResponse(result)
}
}

W/System.err: org.json.JSONException: Value http of type java.lang.String cannot be converted to JSONArray

A script on my server returns an array of SQL rows. An appropriate curl returns string which is correct:
[{"ID":"1","DATETIME":"2021-05-30 21:29:27","SETPOINT":"45.22","LUMIN":"65.98","DIRECTION":"LOG"},{"ID":"1","DATETIME":"2021-05-30 15:55:34","REVS":"2.11934","ROTATION":"1","DIRECTION":"LOG","POSITION":"12"}]
However, while parsing it in my Android application, I am getting an error org.json.JSONException: Value http of type java.lang.String cannot be converted to JSONArray. Closer investigation (Toast printing) to what is passed indicated that the application is receiving the remote script's address http://<ip>/readLatest.php, and not the array, as seen with the curl query.
What seems to be a problem? Other answers as to similar questions were not helpful
Async task:
public class DataGetter extends AsyncTask<String, Void, String[]> {
Context context;
private GetListener GetListener;
public String jsonString;
public boolean passed_successfully;
DataGetter(Context ctx, GetListener listener) {
this.context = ctx;
this.GetListener = listener;
this.passed_successfully = false;
}
#Override
protected String[] doInBackground(String... params) {
String ip = params[0];
String scriptname = params[1];
String db = params[2];
String urladress = "http://" + ip + "/"+ scriptname +".php";
try {
URL url = new URL(urladress);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");
String data = URLEncoder.encode("database", "UTF-8") + "=" + URLEncoder.encode(db, "UTF-8");
writer.write(data);
writer.flush();
writer.close();
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
connection.disconnect();
return new String[] {sb.toString(), scriptname};
} catch (Exception e) {
return new String[] {e.getMessage()};
}
}
#Override
protected void onPostExecute(String... result) {
GetListener.passJSONGet(result);
}
}
Part of appropriate Activity:
#Override
public void passJSONGet(String... result) {
String jsonstring = result[0];
try {
showToast(jsonstring);
this.jsonArray = new JSONArray(jsonstring);
this.printControls(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void printControls(JSONArray jsonArray) throws JSONException {
String lumin = jsonArray.getJSONObject(1).getString("LUMIN");
this.luminval.setText(String.format("%s", lumin));
int position = Integer.parseInt(jsonArray.getJSONObject(0).getString("POSITION"));
this.positionval.setText(String.format("%s", position));
}

How to get json response data using facebook graph api 2.5?

I have a code that brings the json response from the twitter api. I want to use same code for facebook graph api to get json response from the Facebook but facebook doesn't provide any consumer keys as twitter. I can change this code to get the facebook json response. Can any of you help to modify the code.
public class TwitterResponse {
static String AccessToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String AccessSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String ConsumerKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String ConsumerSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
/**
* #param args
*/
public static void main(String[] args) throws Exception
{
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(ConsumerKey,ConsumerSecret);
String twitterUrl="https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=heymailme143&count=1&include_rts=true&contributors=true";
consumer.setTokenWithSecret(AccessToken, AccessSecret);
//HttpGet request = new HttpGet("https://api.twitter.com/1.1/friends/list.json");
HttpGet request = new HttpGet(twitter);
consumer.sign(request);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String m=IOUtils.toString(response.getEntity().getContent());
System.out.println(m);
System.out.println(statusCode + ":" + response.getStatusLine().getReasonPhrase());
}
}
This is a sample code I used to get the twitter response. Could you help me in changing it to get the facebook response using fb graph api?
Have a look at
http://facebook4j.org/en/index.html
which also has some examples.
I'm Looking for this :)
public String getUserInfo(String access_token) throws MalformedURLException, ProtocolException, IOException {
try {
String connection = connectionGet("https://graph.facebook.com/me?access_token=" + access_token, "");
System.out.println("done");
return connection;
} catch (Exception e) {
System.out.println("null value");
return null;
}
}
public static String connectionGet(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {
URL url1 = new URL(url);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setRequestMethod("GET");
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
return responseBody;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
System.out.println(sb.toString());
return sb.toString();
}}

How to send variables to PHP from Android to do a SELECT ... WHERE in PHP

I already got a method to read data from mysql and display it into my android app in textview's. The problem is that now I just retrieve all data from the database without doing a select ... where , just a select. I want to do a select ... where using the variables sent from my android app. I already use the folowing code in my login to send username and pass
nameValuePairs=new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("utilizator",utilizator.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("parola",parola.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
In the method I use I have 2 java files. I really don't understand them much ... so I don't know where to add the code to send variables to php.
httprequest.java
public class httprequest {
static int TIMEOUT = 5000;
public String read_url_resource(String _s_url)
{
String s_response_ = "";
BufferedReader br_reader=null;
StringBuilder sb_builder = new StringBuilder();
URL u_url = null;
try {
if ( _s_url==null || _s_url.length()==0)
return "";
//this.log_message("Downloading from "+_s_url, false);
u_url = new URL(_s_url);
HttpURLConnection huc_urlConnection = null;
huc_urlConnection = (HttpURLConnection)u_url.openConnection();
if ( huc_urlConnection!=null){
huc_urlConnection.setConnectTimeout(TIMEOUT);
huc_urlConnection.setReadTimeout(TIMEOUT);
huc_urlConnection.setUseCaches(false);
huc_urlConnection.setDoOutput(false);
InputStream is_input_stream = huc_urlConnection.getInputStream();
#SuppressWarnings("unused")
URL oURL = huc_urlConnection.getURL();
int i_response_code=huc_urlConnection.getResponseCode();
if ( i_response_code==200){
br_reader = new BufferedReader(new InputStreamReader(is_input_stream));
String line="";
while ((line = br_reader.readLine()) != null)
sb_builder.append(line);
is_input_stream.close();
s_response_ = sb_builder.toString();
String s_auth= huc_urlConnection.getURL().getAuthority();
}
}
} catch (Exception e) {
if ( e!=null )
Log.e("URL PROBLEM", e.toString());
s_response_ = "[\"error\": \"No connection\"]";
}
return s_response_;
}
}
and ReadJSONData.java
public class ReadJSONData extends AsyncTask<String, Integer, Integer> {
private String server = "http://asociatia-online.esy.es/cote.php?hc_location=ufi";
private ReadJSONListener jsonListener;
private String json ="";
private int internal_categ;
httprequest request;
public interface ReadJSONListener
{
void onTaskFinished(String s_json, int _i_internal_category);
}
public ReadJSONData (ReadJSONListener _jsonListener, int _i_internal_category)
{
this.jsonListener=_jsonListener;
this.internal_categ =_i_internal_category;
}
#Override
protected Integer doInBackground(String... strings) {
request = new httprequest();
this.downloadResource();
return null;
}
private void downloadResource() {
switch (this.internal_categ) {
case 1:
this.json = request.read_url_resource(server);
break;
}
}
#Override
protected void onPostExecute(Integer result)
{
this.jsonListener.onTaskFinished(this.json, this.internal_categ);
}
}
So, where to add the 4 lines code to send variables? In which file and where. Thanks !
With this code you can send variables to PHP and get some data back and store it in strings to use as you want.
private class ObtinereInformatii extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://asociatia-online.esy.es/rezumat.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("luna_rezumat",spinner_luna.getSelectedItem().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("an_rezumat",spinner_an.getSelectedItem().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("-------",result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
protected void onPostExecute(String result){
try{
jArray = new JSONArray(result);
readJson(jArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void readJson(JSONArray ja_data) throws JSONException {
if (ja_data!=null)
{
for (int i = 0; i<ja_data.length(); i++)
{
JSONObject jo = ja_data.getJSONObject(i);
if (jo.has("data_rezumat"))
{
if (jo.getString("data_rezumat")!=null)
{
z_data_rezumat= jo.getString("data_rezumat");
}
}
}
}
}

Java - sending HTTP parameters via POST method easily

I am successfully using this code to send HTTP requests with some parameters via GET method
void sendRequest(String request)
{
// i.e.: request = "http://example.com/index.php?param1=a&param2=b&param3=c";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
}
Now I may need to send the parameters (i.e. param1, param2, param3) via POST method because they are very long.
I was thinking to add an extra parameter to that method (i.e. String httpMethod).
How can I change the code above as little as possible to be able to send paramters either via GET or POST?
I was hoping that changing
connection.setRequestMethod("GET");
to
connection.setRequestMethod("POST");
would have done the trick, but the parameters are still sent via GET method.
Has HttpURLConnection got any method that would help?
Is there any helpful Java construct?
Any help would be very much appreciated.
In a GET request, the parameters are sent as part of the URL.
In a POST request, the parameters are sent as a body of the request, after the headers.
To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.
This code should get you started:
String urlParameters = "param1=a&param2=b&param3=c";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "http://example.com/index.php";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
}
Here is a simple example that submits a form then dumps the result page to System.out. Change the URL and the POST params as appropriate, of course:
import java.io.*;
import java.net.*;
import java.util.*;
class Test {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.net/new-message.php");
Map<String,Object> params = new LinkedHashMap<>();
params.put("name", "Freddie the Fish");
params.put("email", "fishie#seamail.example.com");
params.put("reply_to_thread", 10394);
params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish.");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0;)
System.out.print((char)c);
}
}
If you want the result as a String instead of directly printed out do:
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char)c);
String response = sb.toString();
I couldn't get Alan's example to actually do the post, so I ended up with this:
String urlParameters = "param1=a&param2=b&param3=c";
URL url = new URL("http://example.com/index.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
I find HttpURLConnection really cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: DavidWebb.
The above example could be written like this:
Webb webb = Webb.create();
webb.post("http://example.com/index.php")
.param("param1", "a")
.param("param2", "b")
.param("param3", "c")
.ensureSuccess()
.asVoid();
You can find a list of alternative libraries on the link provided.
import java.net.*;
public class Demo{
public static void main(){
String data = "data=Hello+World!";
URL url = new URL("http://localhost:8084/WebListenerServer/webListener");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.getOutputStream().write(data.getBytes("UTF-8"));
con.getInputStream();
}
}
i have read above answers and have created a utility class to simplify HTTP request. i hope it will help you.
Method Call
// send params with Hash Map
HashMap<String, String> params = new HashMap<String, String>();
params.put("email","me#example.com");
params.put("password","12345");
//server url
String url = "http://www.example.com";
// static class "HttpUtility" with static method "newRequest(url,method,callback)"
HttpUtility.newRequest(url,HttpUtility.METHOD_POST,params, new HttpUtility.Callback() {
#Override
public void OnSuccess(String response) {
// on success
System.out.println("Server OnSuccess response="+response);
}
#Override
public void OnError(int status_code, String message) {
// on error
System.out.println("Server OnError status_code="+status_code+" message="+message);
}
});
Utility Class
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import static java.net.HttpURLConnection.HTTP_OK;
public class HttpUtility {
public static final int METHOD_GET = 0; // METHOD GET
public static final int METHOD_POST = 1; // METHOD POST
// Callback interface
public interface Callback {
// abstract methods
public void OnSuccess(String response);
public void OnError(int status_code, String message);
}
// static method
public static void newRequest(String web_url, int method, HashMap < String, String > params, Callback callback) {
// thread for handling async task
new Thread(new Runnable() {
#Override
public void run() {
try {
String url = web_url;
// write GET params,append with url
if (method == METHOD_GET && params != null) {
for (Map.Entry < String, String > item: params.entrySet()) {
String key = URLEncoder.encode(item.getKey(), "UTF-8");
String value = URLEncoder.encode(item.getValue(), "UTF-8");
if (!url.contains("?")) {
url += "?" + key + "=" + value;
} else {
url += "&" + key + "=" + value;
}
}
}
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // handle url encoded form data
urlConnection.setRequestProperty("charset", "utf-8");
if (method == METHOD_GET) {
urlConnection.setRequestMethod("GET");
} else if (method == METHOD_POST) {
urlConnection.setDoOutput(true); // write POST params
urlConnection.setRequestMethod("POST");
}
//write POST data
if (method == METHOD_POST && params != null) {
StringBuilder postData = new StringBuilder();
for (Map.Entry < String, String > item: params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(item.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(item.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
urlConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
urlConnection.getOutputStream().write(postDataBytes);
}
// server response code
int responseCode = urlConnection.getResponseCode();
if (responseCode == HTTP_OK && callback != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// callback success
callback.OnSuccess(response.toString());
reader.close(); // close BufferReader
} else if (callback != null) {
// callback error
callback.OnError(responseCode, urlConnection.getResponseMessage());
}
urlConnection.disconnect(); // disconnect connection
} catch (IOException e) {
e.printStackTrace();
if (callback != null) {
// callback error
callback.OnError(500, e.getLocalizedMessage());
}
}
}
}).start(); // start thread
}
}
I see some other answers have given the alternative, I personally think that intuitively you're doing the right thing ;). Sorry, at devoxx where several speakers have been ranting about this sort of thing.
That's why I personally use Apache's HTTPClient/HttpCore libraries to do this sort of work, I find their API to be easier to use than Java's native HTTP support. YMMV of course!
GET and POST method set like this... Two types for api calling 1)get() and 2) post() . get() method to get value from api json array to get value & post() method use in our data post in url and get response.
public class HttpClientForExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpClientExample http = new HttpClientExample();
System.out.println("Testing 1 - Send Http GET request");
http.sendGet();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}
// HTTP GET request
private void sendGet() throws Exception {
String url = "http://www.google.com/search?q=developer";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
urlParameters.add(new BasicNameValuePair("cn", ""));
urlParameters.add(new BasicNameValuePair("locale", ""));
urlParameters.add(new BasicNameValuePair("caller", ""));
urlParameters.add(new BasicNameValuePair("num", "12345"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
}
I had the same issue. I wanted to send data via POST.
I used the following code:
URL url = new URL("http://example.com/getval.php");
Map<String,Object> params = new LinkedHashMap<>();
params.put("param1", param1);
params.put("param2", param2);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
String urlParameters = postData.toString();
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String result = "";
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
result += line;
}
writer.close();
reader.close()
System.out.println(result);
I used Jsoup for parse:
Document doc = Jsoup.parseBodyFragment(value);
Iterator<Element> opts = doc.select("option").iterator();
for (;opts.hasNext();) {
Element item = opts.next();
if (item.hasAttr("value")) {
System.out.println(item.attr("value"));
}
}
Try this pattern:
public static PricesResponse getResponse(EventRequestRaw request) {
// String urlParameters = "param1=a&param2=b&param3=c";
String urlParameters = Piping.serialize(request);
HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);
PricesResponse response = null;
try {
// POST
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
// RESPONSE
BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
String json = Buffering.getString(reader);
response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);
writer.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
conn.disconnect();
System.out.println("PricesClient: " + response.toString());
return response;
}
public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) {
return RestClient.getConnection(endPoint, "POST", urlParameters);
}
public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) {
System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
HttpURLConnection conn = null;
try {
URL url = new URL(endPoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/plain");
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
This answer covers the specific case of the POST Call using a Custom Java POJO.
Using maven dependency for Gson to serialize our Java Object to JSON.
Install Gson using the dependency below.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
<scope>compile</scope>
</dependency>
For those using gradle can use the below
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
Other imports used:
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.*;
import org.apache.http.impl.client.CloseableHttpClient;
import com.google.gson.Gson;
Now, we can go ahead and use the HttpPost provided by Apache
private CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://example.com");
Product product = new Product(); //custom java object to be posted as Request Body
Gson gson = new Gson();
String client = gson.toJson(product);
httppost.setEntity(new StringEntity(client, ContentType.APPLICATION_JSON));
httppost.setHeader("RANDOM-HEADER", "headervalue");
//Execute and get the response.
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (IOException e) {
throw new InternalServerErrorException("Post fails");
}
Response.Status responseStatus = Response.Status.fromStatusCode(response.getStatusLine().getStatusCode());
return Response.status(responseStatus).build();
The above code will return with the response code received from the POST Call
here i sent jsonobject as parameter //jsonobject={"name":"lucifer","pass":"abc"}//serverUrl = "http://192.168.100.12/testing" //host=192.168.100.12
public static String getJson(String serverUrl,String host,String jsonobject){
StringBuilder sb = new StringBuilder();
String http = serverUrl;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(50000);
urlConnection.setReadTimeout(50000);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Host", host);
urlConnection.connect();
//You Can also Create JSONObject here
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonobject);// here i sent the parameter
out.close();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
Log.e("new Test", "" + sb.toString());
return sb.toString();
} else {
Log.e(" ", "" + urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return null;
}
Hello pls use this class to improve your post method
public static JSONObject doPostRequest(HashMap<String, String> data, String url) {
try {
RequestBody requestBody;
MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
if (data != null) {
for (String key : data.keySet()) {
String value = data.get(key);
Utility.printLog("Key Values", key + "-----------------" + value);
mBuilder.addFormDataPart(key, value);
}
} else {
mBuilder.addFormDataPart("temp", "temp");
}
requestBody = mBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Utility.printLog("URL", url);
Utility.printLog("Response", responseBody);
return new JSONObject(responseBody);
} catch (UnknownHostException | UnsupportedEncodingException e) {
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
} catch (JSONException e1) {
e1.printStackTrace();
}
Log.e(TAG, "Error: " + e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
} catch (JSONException e1) {
e1.printStackTrace();
}
Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
}
return null;
}
I higly recomend http-request built on apache http api.
For your case you can see example:
private static final HttpRequest<String.class> HTTP_REQUEST =
HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer())
.build();
public void sendRequest(String request){
String parameters = request.split("\\?")[1];
ResponseHandler<String> responseHandler =
HTTP_REQUEST.executeWithQuery(parameters);
System.out.println(responseHandler.getStatusCode());
System.out.println(responseHandler.get()); //prints response body
}
If you are not interested in the response body
private static final HttpRequest<?> HTTP_REQUEST =
HttpRequestBuilder.createPost("http://example.com/index.php").build();
public void sendRequest(String request){
ResponseHandler<String> responseHandler =
HTTP_REQUEST.executeWithQuery(parameters);
}
For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java
I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:
public static byte[] httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException {
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : postsData.entrySet()) {
if (postData.length() != 0) postData.append('&');
Object value = param.getValue();
String key = param.getKey();
if(value instanceof Object[] || value instanceof List<?>)
{
int size = value instanceof Object[] ? ((Object[])value).length : ((List<?>)value).size();
for(int i = 0; i < size; i++)
{
Object val = value instanceof Object[] ? ((Object[])value)[i] : ((List<?>)value).get(i);
if(i>0) postData.append('&');
postData.append(URLEncoder.encode(key + "[" + i + "]", "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(val), "UTF-8"));
}
}
else
{
postData.append(URLEncoder.encode(key, "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(value), "UTF-8"));
}
}
return postData.toString().getBytes("UTF-8");
}
For those having trouble receiving the request on a php page using $_POST because you expect key-value pairs:
While all the answers where very helpful, I lacked some basic understanding on which string actually to post, since in the old apache HttpClient I used
new UrlEncodedFormEntity(nameValuePairs); (Java)
and then could use $_POST in php do get the key-value pairs.
To my understanding now one has build that string manually before posting. So the string needs to look like
val data = "key1=val1&key2=val2"
but instead just adding it to the url it is posted (in the header).
The alternative would be to use a json-string instead:
val data = "{\"key1\":\"val1\",\"key2\":\"val2\"}" // {"key1":"val1","key2":"val2"}
and pull it in php without $_POST:
$json_params = file_get_contents('php://input');
// echo_p("Data: $json_params");
$data = json_decode($json_params, true);
Here you find a sample code in Kotlin:
class TaskDownloadTest : AsyncTask<Void, Void, Void>() {
override fun doInBackground(vararg params: Void): Void? {
var urlConnection: HttpURLConnection? = null
try {
val postData = JsonObject()
postData.addProperty("key1", "val1")
postData.addProperty("key2", "val2")
// reformat json to key1=value1&key2=value2
// keeping json because I may change the php part to interpret json requests, could be a HashMap instead
val keys = postData.keySet()
var request = ""
keys.forEach { key ->
// Log.i("data", key)
request += "$key=${postData.get(key)}&"
}
request = request.replace("\"", "").removeSuffix("&")
val requestLength = request.toByteArray().size
// Warning in Android 9 you need to add a line in the application part of the manifest: android:usesCleartextTraffic="true"
// https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted
val url = URL("http://10.0.2.2/getdata.php")
urlConnection = url.openConnection() as HttpURLConnection
// urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") // apparently default
// Not sure what these are for, I do not use them
// urlConnection.setRequestProperty("Content-Type", "application/json")
// urlConnection.setRequestProperty("Key","Value")
urlConnection.readTimeout = 5000
urlConnection.connectTimeout = 5000
urlConnection.requestMethod = "POST"
urlConnection.doOutput = true
// urlConnection.doInput = true
urlConnection.useCaches = false
urlConnection.setFixedLengthStreamingMode(requestLength)
// urlConnection.setChunkedStreamingMode(0) // if you do not want to handle request length which is fine for small requests
val out = urlConnection.outputStream
val writer = BufferedWriter(
OutputStreamWriter(
out, "UTF-8"
)
)
writer.write(request)
// writer.write("{\"key1\":\"val1\",\"key2\":\"val2\"}") // {"key1":"val1","key2":"val2"} JsonFormat or just postData.toString() for $json_params=file_get_contents('php://input'); json_decode($json_params, true); in php
// writer.write("key1=val1&key2=val2") // key=value format for $_POST in php
writer.flush()
writer.close()
out.close()
val code = urlConnection.responseCode
if (code != 200) {
throw IOException("Invalid response from server: $code")
}
val rd = BufferedReader(
InputStreamReader(
urlConnection.inputStream
)
)
var line = rd.readLine()
while (line != null) {
Log.i("data", line)
line = rd.readLine()
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
urlConnection?.disconnect()
}
return null
}
}
Now I had to do an HTTP request class, it is probably not the most efficient class, but it works.
I collected some codes from this page and made it more dynamic.
Anyone who needs a complete code, I attached it below.
For an example of how to use it, you can look at the main method.
Also, if you are willing to improve classes online, you are more than welcome to help me make this class better.
import java.net.*;
import java.util.*;
import java.nio.charset.*;
import java.io.*;
public class HttpRequest {
String result = "";
HttpRequest(String _url, String _method, Map<String, String> _postData, String _contentType) {
try {
URL url = new URL( _url );
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod(_method); // PUT is another valid option
http.setDoOutput(true);
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : _postData.entrySet())
sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + entry.getValue());
//sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue()));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", _contentType);
http.setRequestProperty( "charset", "utf-8");
http.setRequestProperty( "Content-Length", Integer.toString( length ));
http.setInstanceFollowRedirects( false );
http.setUseCaches( false );
http.connect();
try(OutputStream os = http.getOutputStream()) {
os.write(out);
}
if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(http.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
result = result + line;
}
}
} else {
System.out.println("Bad response!");
}
}catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
HttpRequest(String _url, String _method, Map<String, String> _postData) {
this(_url, _method, _postData, "text/html");
}
HttpRequest(String _url, String _method) {
this(_url, _method, new HashMap<String, String>());
}
HttpRequest(String _url) {
this(_url, "GET");
}
public String toString() {
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, String> postData = new HashMap<String, String>();
postData.putIfAbsent("email", "test#test.com");
postData.putIfAbsent("password", "test");
HttpRequest result = new HttpRequest("https://httpbin.org/anything", "POST", postData, "application/x-www-form-urlencoded");
System.out.println(result.toString());
}
}
Appears that you also have to callconnection.getOutputStream() "at least once" (as well as setDoOutput(true)) for it to treat it as a POST.
So the minimum required code is:
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
connection.connect();
connection.getOutputStream().close();
You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.
You can also use NameValuePair apparently.

Categories