i am trying to do an android app to write some datas on MySQL database but it does not work i did a Java class for this and i think the problem comes from this. Here is my code :
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
BackgroundTask(Context ctx) {this.ctx = ctx;}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://localhost:8080/project/register.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String password = params[2];
String contact = params[3];
String country = params[4];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(contact, "UTF-8") + "&" +
URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Actually what i would like is to save name, password, contact and country in my database. The problem is this : "Registration success" is never returned it is always null. But i don't know why. When i try to compile it looks like there is no errors and i can see the app.
Thank you very much for your help !
Edit : This is the register.php :
<?php
require "init.php";
$u_name=$_POST["name"];
$u_password=$_POST["password"];
$u_contact=$_POST["contact"]";
$u_country=$_POST["country"];
$sql_query="insert into users values('$u_name', '$u_password', '$u_contact', '$u_country');";
//mysqli_query($connection, $sql_query));
if(mysqli_query($connection,$sql_query))
{
//echo "data inserted";
}
else{
//echo "error";
}
?>
And also the init.php :
<?php
$db_name = "project";
$mysql_user = "root";
$server_name = "localhost";
$connection = mysqli_connect($server_name, $mysql_user, "", $db_name);
if(!$connection){
echo "Connection not successful";
}
else{
echo "Connection successful";
}
?>
Thank you for your help !
My class PutUtility for getData(), PostData, DeleteData(). you just need to change package name
package fourever.amaze.mics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class PutUtility {
private Map<String, String> params = new HashMap<>();
private static HttpURLConnection httpConnection;
private static BufferedReader reader;
private static String Content;
private StringBuffer sb1;
private StringBuffer response;
public void setParams(Map<String, String> params) {
this.params = params;
}
public void setParam(String key, String value) {
params.put(key, value);
}
public String getData(String Url) {
StringBuilder sb = new StringBuilder();
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) { }
}
return response.toString();
}
public String postData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
value = params.get(key);
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return response.toString();
}
public String putData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
try {
value = URLEncoder.encode(params.get(key), "UTF-8");
if (value.contains("+"))
value = value.replace("+", "%20");
//return sb.toString();
// Get the server response
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send PUT data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("PUT");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(false);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
;
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
// Send PUT data request
return Url;
}
public String deleteData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("DELETE");
httpConnection.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
}
return Url;
}
}
And use this class like this
#Override
protected String doInBackground(String... params) {
res = null;
PutUtility put = new PutUtility();
put.setParam("ueid", params[0]);
put.setParam("firm_no", params[1]);
put.setParam("date_incorporation", params[2]);
put.setParam("business_name", params[3]);
put.setParam("block_no", params[4]);
try {
res = put.postData(
"Api URL here");
Log.v("res", res);
} catch (Exception objEx) {
objEx.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(String res) {
try {
} catch (Exception objEx) {
mProgressDialog.dismiss();
objEx.printStackTrace();
}
}
Please use this. Hope it helps you in future also.
Check this if this is the problem
$u_contact=$_POST["contact"]"
here is the problem i think so brother. replace with
$u_contact=$_POST["contact"];
Related
I am trying to fetch the application only bearer token by using my consumer key and consumer secret following this. This is my implementation:
public class OAuthApplicationOnlyBearerTokenFetchTask extends AsyncTask<String, Void, String> {
private static Logger logger =
Logger.getLogger(OAuthApplicationOnlyBearerTokenFetchTask.class.getName());
final static String URL_TWITTER_OAUTH2_TOKEN = "https://api.twitter.com/oauth2/token";
final static String USER_AGENT = "TwitterMotion User Agent";
protected String mApplicationOnlyBearerToken;
#Override
protected String doInBackground(String... tokens) {
String consumerKey = tokens[0];
String consumerSecret = tokens[0];
String encodedCredentials = encodeKeysFrom(consumerKey, consumerSecret);
HttpURLConnection urlConnection = null;
try {
URL url = new URL(URL_TWITTER_OAUTH2_TOKEN);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Host", "api.twitter.com");
urlConnection.setRequestProperty("User-Agent", USER_AGENT);
urlConnection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
urlConnection.setRequestProperty("Content-Length", "29");
urlConnection.setUseCaches(false);
writeRequest(urlConnection, "grant_type=client_credentials");
String jsonResponse = readResponse(urlConnection);
logger.log(INFO, "jsonResponse of the bearer oauth request: ", jsonResponse);
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
logger.log(Level.SEVERE, "HTTP 403 (Forbidden) returned from Twitter API call for bearer token. " +
"Check values of Consumer Key and Consumer Secret in tokens.properties");
throw new RejectedAuthorizationException(urlConnection.getResponseCode(), "HTTP 403 (Forbidden) returned attempting to get Twitter API bearer token");
}
JSONObject jsonResponseObject = new JSONObject(jsonResponse);
if (jsonResponseObject != null) {
mApplicationOnlyBearerToken = (String) jsonResponseObject.get("access_token");
} else {
// TODO
}
return mApplicationOnlyBearerToken;
} catch (Exception ex) {
logger.log(Level.SEVERE, "", ex);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(String applicationOnlyBearerToken) {
this.mApplicationOnlyBearerToken = applicationOnlyBearerToken;
}
public String getApplicationOnlyBearerToken() {
return mApplicationOnlyBearerToken;
}
private String encodeKeysFrom(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8");
String combinedEncodedKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encode(combinedEncodedKey.getBytes(), Base64.NO_WRAP);
return new String(encodedBytes);
}
catch (UnsupportedEncodingException e) {
// TODO
return null;
}
}
private boolean writeRequest(HttpURLConnection connection, String requestBody)
throws IOException {
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(connection.getOutputStream()));
bufferedWriter.write(requestBody);
bufferedWriter.flush();
return true;
}
catch (IOException ex) {
return false;
}
finally {
if (bufferedWriter != null) {
bufferedWriter.close();
}
}
}
private String readResponse(HttpURLConnection connection) throws IOException {
BufferedReader bufferedReader = null;
try {
StringBuilder stringBuilder = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + System.getProperty("line.separator"));
}
return stringBuilder.toString();
}
catch (IOException e) {
return null;
}
finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
}
}
But I am getting HTTP 403 Forbidden.
I also added permission on manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I can not understand what is the issue actually. Thanks in advance!
Never mind, I've found the bug.
String consumerKey = tokens[0];
String consumerSecret = tokens[0];
It should be
String consumerSecret = tokens[1];
My question is how to add basic auth Java Android AsyncTask? Some of developers said it needs to be declared in RequestHandler.java or in doInBackground AsyncTask function. Below is my code:
private void loginTask(String _username, String _password){
final String username = _username;
final String password = _password;
class LoginTask extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(LoginActivity.this,"Fetching...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(App.URL_AUTHENTICATION);
Toast.makeText(LoginActivity.this, s.toString(), Toast.LENGTH_SHORT).show();
return s;
}
}
LoginTask gt = new LoginTask();
gt.execute();
}
RequestHandler class: https://github.com/IntellijSys/AndroidToDoList/blob/master/app/src/main/java/my/intellij/androidtodolist/RequestHandler.java
Try this
RequestHandler rh = new RequestHandler();
// your basic auth username and password
rh.setBasicAuth("username","password");
String s = rh.sendGetRequest(App.URL_AUTHENTICATION);
RequestHandler class with Basic auth
import android.util.Base64;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by ZERO on 16/08/2016.
*/
public class RequestHandler {
private String username;
private String password;
//Method to send httpPostRequest
//This method is taking two arguments
//First argument is the URL of the script to which we will send the request
//Other is an HashMap with name value pairs containing the data to be send with the request
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try {
//Initializing Url
url = new URL(requestURL);
//Creating an httmlurl connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//set Basic auth
processBasicAuth(conn);
//Configuring connection properties
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Creating an output stream
OutputStream os = conn.getOutputStream();
//Writing parameters to the request
//We are using a method getPostDataString which is defined below
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null) {
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
private void processBasicAuth(HttpURLConnection conn) {
if (username != null && password != null) {
try {
String userPassword = username + ":" + password;
byte[] data = userPassword.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
conn.setRequestProperty("Authorization", "Basic " + base64);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
public String sendGetRequest(String requestURL) {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(requestURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//set Basic auth
processBasicAuth(con);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while ((s = bufferedReader.readLine()) != null) {
sb.append(s + "\n");
}
} catch (Exception e) {
}
return sb.toString();
}
public String sendGetRequestParam(String requestURL, String id) {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(requestURL + id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while ((s = bufferedReader.readLine()) != null) {
sb.append(s + "\n");
}
} catch (Exception e) {
}
return sb.toString();
}
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 void setBasicAuth(String username, String password) {
this.username = username;
this.password = password;
}
}
I have been working on the following code for a while.
the code worked for the 5.x version of my app but I can't get the code to work for Android version 6.x and higher.
public class PostAsync extends AsyncTask<String, Integer, Double> {
private Context _context = null;
public PostAsync(Context context) {
_context = context;
}
#Override
protected Double doInBackground(String... params) {
String serverResponse = postData(params[0]);
try {
JSONObject obj = new JSONObject(serverResponse);
String id = "";
JSONObject locationobj = obj.getJSONObject("X");
JSONObject response = locationobj.getJSONObject("Y");
id = response.getString("id");
Settings.idcode = id;
// Convert , to %2c, since we're working with a URI here
String number = Settings.number + Settings.code + "," + Settings.idcode; // %2c
_context.startActivity(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel://" + number)));
}
catch (Exception e) {
// TODO: Errorhandler
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
}
protected void onProgressUpdate(Integer... progress) {
}
// Send a POST request to specified url in Settings class, with defined JSONObject message
public String postData(String msg) {
String result = null;
StringBuffer sb = new StringBuffer();
InputStream is = null;
try {
URL url = new URL(Settings.webURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setChunkedStreamingMode(0);
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestProperty("Content-Encoding", "identity");
connection.setRequestProperty("Accept-Encoding", "identity");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("TYPE", "JSON");
connection.setRequestProperty("KEY", "key");
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(msg);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
System.out.println("Response code: " + responseCode);
System.out.println("Response message: " + responseMessage);
if(responseCode == HttpURLConnection.HTTP_OK){
is = new BufferedInputStream(connection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
try {
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
result = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
I get the following error
java.net.ProtocolException: Unexpected status line: HTTP/1.2 200 OK
Can someone tell me what I am missing?
I'm trying to send POST request via HttpURLConnection, here is the code
public class BackgroundTask extends AsyncTask<String, Void, Void> {
Context context;
Activity activity;
StringBuffer str = null;
int responseCode;
String responseMessage;
public BackgroundTask(Context context) {
this.context = context;
this.activity = (Activity) context;
}
#Override
protected Void doInBackground(String... params) {
HttpURLConnection connection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
BufferedReader reader = null;
BufferedWriter writer = null;
String method = params[1];
if(method.equals("post")) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
outputStream = connection.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
writer.write(data);
responseCode = connection.getResponseCode();
responseMessage = connection.getResponseMessage();
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
str = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
str.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else if(method.equals("get")) {
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void aVoid) {
TextView txt = (TextView) activity.findViewById(R.id.txt);
if(str != null)
txt.setText(str.toString());
Toast.makeText(activity, responseMessage, Toast.LENGTH_LONG).show();
}
}
responseCode is 200 which means everything went OK, however it says Undefined index: id
id is well defined inside php file
$user = User::find_by_id($_POST['id']);
echo json_encode($user);
and it works fine when I send post request from an html file yet when i send it from application it says id undefined which means that POST data is not sent.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask myTask = new BackgroundTask(MainActivity.this);
myTask.execute(link, "post", "id", "5");
}
});
this is how i instantiate asynctask object inside main activity
UPDATE: when i send not encoded string it works fine!
writer.write("id=5"); // works perfectly!
what is wrong with URLEncoder i use in the code?
I believe you have a problem in this line:
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
You are url-encoding the = as well as the params, that's why the server cannot recognise the form fields. Try to encode the params only:
String data = URLEncoder.encode(params[2], "UTF-8") + "=" + URLEncoder.encode(params[3], "UTF-8");
The reason is that URL encoding is for passing special characters like = in the value(or key). Basically, the server will split and parse the key-value pairs with & and = before doing the decoding. And when you url-encode the = character, the server simply couldn't recognise it during the split and parse phase.
When i need to communicate with the server i use this
Server Class
public static String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static 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();
}
OtherClass
//Run this inside an Asynctask
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
String serverResponce = Server.sendPostRequest(URL,data);
I tried use search tweets use twitter search api.
But when i get bearer token then send request to
/1.1/search/tweets.json?count=2
Its response is 400 (Bad Request)
I don't know how is wrong... Anyone can help me ??
Here is my Code all from http://www.coderslexicon.com/demo-of-twitter-application-only-oauth-authentication-using-java/
I also watch Application-only authentication but still don't know why.
Hope someone can tell me ....
private final static String getTokenURL = "https://api.twitter.com/oauth2/token";
private static String bearerToken;
static final String ACCESS_TOKEN = "1111111112-H************************************s";
static final String ACCESS_SECRET = "S************************************n";
static final String CONSUMER_KEY = "q************************************g";
static final String CONSUMER_SECRET = "Q************************************a";
public static void main(String[] args) {
new Thread(new Runnable() {
#Override
public void run() {
try {
bearerToken = requestBearerToken(getTokenURL);
searchTweets("https://api.twitter.com/1.1/search/tweets.json?count=2");
} catch (IOException e) {
System.out.println("IOException e");
e.printStackTrace();
}
}
}).start();
}
private static String encodeKeys(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret,
"UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
} catch (UnsupportedEncodingException e) {
return new String();
}
}
private static String requestBearerToken(String endPointUrl)
throws IOException {
HttpsURLConnection connection = null;
String encodedCredentials = encodeKeys(CONSUMER_KEY, CONSUMER_SECRET);
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
System.out.println(connection);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "MwTestTwitterAPI");
connection.setRequestProperty("Authorization", "Basic "
+ encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
writeRequest(connection, "grant_type=client_credentials");
System.out.println(connection.getResponseCode());
System.out.println(connection.getResponseMessage());
String result = readResponse(connection);
JSONObject jsonResult=new JSONObject(result);
if (jsonResult.get("token_type") != null && jsonResult.get("token_type").equals("bearer") ) {
return jsonResult.getString("access_token");
}
return new String();
} catch (MalformedURLException | JSONException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private static String searchTweets(String endPointUrl) throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "MwTestTwitterAPI");
connection.setRequestProperty("Authorization", "Bearer " + bearerToken);
connection.setUseCaches(false);
String result = readResponse(connection);
System.out.println("fetchTimelineTweet---result:"+result);
if (result != null || result.equals("")) {
return result;
}
return new String();
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
// Writes a request to a connection
private static boolean writeRequest(HttpURLConnection connection,
String textBody) {
try {
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
} catch (IOException e) {
return false;
}
}
// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpURLConnection connection) {
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
} catch (IOException e) {
return new String();
}
}
You're missing a query variable q, which is a required parameter.
Try changing your request url to: https://api.twitter.com/1.1/search/tweets.json?count=2&q=test