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?
Related
I am working on an application that interacts with a room security control device.
I want to get devices information from API. I am using HttpUrlConnection and POST method. It hits the API and I get 200 OK response but I get the out
"{"json":{"control":{"cmd":"getdevice","uid":256}}} doesn't exist"
I have tried all the solutions from stackoverflow and other platforms but it's not giving the output.
Moreover I have tested this API on Postman and it's working there and giving the device information.
Here is the code:
public class HTTPRequestTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
String username = "admin";
String password = "888888";
URL url = null;
try {
url = new URL("http://192.168.100.25/network.cgi");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
HttpURLConnection httpRequest = null;
try {
httpRequest = (HttpURLConnection) url.openConnection();
httpRequest.setRequestMethod("POST");
httpRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setDoInput(true);
httpRequest.setDoOutput(true);
android.util.Base64.encode(authString.getBytes(), android.util.Base64.DEFAULT);
httpRequest.addRequestProperty("Authorization", "Basic " + "YWRtaW46ODg4ODg4"); // This is auth bytecode
httpRequest.connect();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject json = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONObject jsonObjectControl = new JSONObject();
jsonObjectControl.put("cmd","getdevice");
jsonObjectControl.put("uid",256);
jsonObject.put("control",jsonObjectControl);
json.put("json", jsonObject);
String encodedData = URLEncoder.encode( json.toString(), "UTF-8" );
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpRequest.getOutputStream()));
writer.write(encodedData);
writer.flush();
BufferedReader bufferedReader = null;
bufferedReader = new BufferedReader
(new InputStreamReader(httpRequest.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
do {
line = bufferedReader.readLine();
sb.append(line);
Log.i("Output line: ",sb.toString());
}
while(bufferedReader.readLine()!=null);
bufferedReader.close();
int responseCode = httpRequest.getResponseCode();
String resMsg = httpRequest.getResponseMessage();
String result = sb.toString();
Log.d("Output: ","--"+result);
Log.d("Response Code: "+responseCode, "!!");
Log.d("Response MSG ","--"+resMsg);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
I am trying to use geo location api to get lattitude and longitude of the location. So for this I created a project on developer console and created an api key. I used this api key with this api https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY
So this when I executed the request in postman it works well.
But when I tried to execute same request in an app its giving response as response code 400.
Response code 400 as per developer guide
https://developers.google.com/maps/documentation/geolocation/intro#errors
shows it comes when the api key is wrong. But how the key works in postman and not in the app?
Here is the code for server request:
public JSONObject sendPostRequest1(String data) {
try {
URL url = new URL(api);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
// con.setRequestProperty("content-type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
try {
writer.write(data);
} catch (Exception e) {
Log.e("Exception111", e.toString());
}
writer.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
Log.d("ServerResponse", new String(sb));
String output = new String(sb);
return new JSONObject(output);
} else {
Log.e("Exception", "" + responseCode);
}
}
catch (JSONException je)
{
je.printStackTrace();
return Excpetion2JSON.getJSON(je);
}
catch(IOException e)
{
}
return null;
}
Async Task :
public class GetLocationAsyncTask extends AsyncTask<String, Void, JSONObject> {
String api;
JSONObject jsonParams;
Context mContext;
private ProgressDialog loadingDialog;
private String number,code;
public GetLocationsCallBack getLocationsCallBack;
public GetLocationAsyncTask(Context context,GetLocationsCallBack getLocationsCallBack) {
this.mContext = context;
this.getLocationsCallBack = getLocationsCallBack;
}
public interface GetLocationsCallBack {
void doPostExecute(ArrayList<Location> list);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCArRAX4oHdfFWrTWhXrOVBQtbs";
jsonParams = new JSONObject();
jsonParams.put("cellId", params[0]);
jsonParams.put("locationAreaCode",params[1]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendPostRequest1(jsonParams.toString());
} catch (Exception ue) {
return Excpetion2JSON.getJSON(ue);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
if(response.has("location"))
{
try {
Location location = new Location();
location.setLattitude(response.getString("lat"));
location.setLongitude(response.getString("lng"));
ArrayList<Location> locations = location.getLocationArrayList();
locations.add(location);
}
catch (JSONException je)
{
Log.d("JsonException",je.toString());
}
}
if (loadingDialog.isShowing())
loadingDialog.dismiss();
}
}
Executing async task:
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
int cellid= cellLocation.getCid();
int celllac = cellLocation.getLac();
Log.d("CellLocation", cellLocation.toString());
Log.d("GSM CELL ID", String.valueOf(cellid));
Log.d("GSM Location Code", String.valueOf(celllac));
GetLocationAsyncTask getLocationAsyncTask = new GetLocationAsyncTask(MainActivity.this,MainActivity.this);
getLocationAsyncTask.execute(String.valueOf(cellid),String.valueOf(celllac));
Whats going wrong with this? Please help. Thank you..
You have to tell the receiving side that it is json that you send
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
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"];
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