I am new to android.So i can any one sho me how to make a http get request such as
GET /photos?size=original&file=vacation.jpg HTTP/1.1
Host: photos.example.net:80
Authorization: OAuth realm="http://photos.example.net/photos",
oauth_consumer_key="dpf43f3p2l4k3l03",
oauth_token="nnch734d00sl2jdk",
oauth_nonce="kllo9940pd9333jh",
oauth_timestamp="1191242096",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D"
in android(java)?
You're gonna want to get familiar with InputStreams and OutputStreams in Android, if you've done this in regular java before then its essentially the same thing. You need to open a connection with the request property as "GET", you then write your parameters to the output stream and read the response through an input stream. You can see this in my code below:
try {
URL url = null;
String response = null;
String parameters = "param1=value1¶m2=value2";
url = new URL("http://www.somedomain.com/sendGetData.php");
//create the connection
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
//set the request method to GET
connection.setRequestMethod("GET");
//get the output stream from the connection you created
request = new OutputStreamWriter(connection.getOutputStream());
//write your data to the ouputstream
request.write(parameters);
request.flush();
request.close();
String line = "";
//create your inputsream
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
//read in the data from input stream, this can be done a variety of ways
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//get the string version of the response data
response = sb.toString();
//do what you want with the data now
//always remember to close your input and output streams
isr.close();
reader.close();
} catch (IOException e) {
Log.e("HTTP GET:", e.toString());
}
Related
I'm using HttpURLConnection to send a POST request to get the access token. However, I get the error says
java.io.IOException: Server returned HTTP response code: 401 for URL: https://xyz.auth0.com/oauth/token
Note: I'm able to get the access token via Postman.
Can someone please help me? Thanks in advance!
public String requestToken() throws Exception{
StringBuilder response = new StringBuilder();
URL url = new URL("https://xyz.auth0.com/oauth/token");
//open a connection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//set the request method
connection.setRequestMethod(TokenConstant.METHOD_POST);
//set the request content-type header parameter
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
//set response format type
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
//create request parameter
String jsonInputString = "grant_type=client_credentials&client_id=xyz&client_secret=abc&audience=https://xyz.abc.com}";;
// we need to write it
try(OutputStream outputStream = connection.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
//Read the response from Input Stream
//get the input stream to read the response content
try(BufferedReader br = new BufferedReader(
new InputStreamReader(
connection.getInputStream(),"utf-8"))){
String responseLine = null;
while((responseLine = br.readLine()) != null){
response.append(responseLine.trim());
}
}
return response.toString();
}
Sample curl facebook oauth access token generation (GET request) - To generate an app access token:
curl -X GET "https://graph.facebook.com/oauth/access_token
?client_id={your-app-id}
&client_secret={your-app-secret}
&grant_type=client_credentials"
Commented few headers - Not required. Changed request to GET.
NOTE: if it works fine with curl, then your code might work fine, with few modifications.
public static String requestToken() throws Exception{
StringBuilder response = new StringBuilder();
URL url = new URL("https://graph.facebook.com/oauth/access_token");
//open a connection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//set the request method
connection.setRequestMethod("GET");
//set the request content-type header parameter
// Commented - not required
/*connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");*/
//set response format type
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
//create request parameter
String jsonInputString = "client_id=<your-app-id>&client_secret=<your-app-secret>&grant_type=client_credentials";;
// we need to write it
try(OutputStream outputStream = connection.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
//Read the response from Input Stream
//get the input stream to read the response content
try(BufferedReader br = new BufferedReader(
new InputStreamReader(
connection.getInputStream(),"utf-8"))){
String responseLine = null;
while((responseLine = br.readLine()) != null){
response.append(responseLine.trim());
}
}
return response.toString();
}
I am trying to create my first android application that utilizes a REST api. My api is written in Node.JS and has already been tested using Postman, however, I am having trouble sending JSON data to my api.
#Override
protected String doInBackground(String... params) {
String data = "";
String urlName = params[0];
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(urlName).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
I always reach the line that declares and initializes my DataOutputSteam and doesn't execute the code. I am not even getting a log that my Virtual device has visited my server at all.
I have included in the manifest XML both of these already.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Based on your logs, you're hitting a NetworkOnMainThreadException and that's preventing the network request from being executed (it's going into your catch block instead). This suggests you aren't calling your AsyncTask correctly - ensure that you're calling execute instead of calling doInBackground. See also here for more information on this general pattern.
Try this, it is for POST method that accept 2 parameter email and password.
Change it based on your requirement
URL url = new URL(Login_url);
HttpURLConnection conn = (HttpURLConnection) new URL(urlName).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept" , "application/json");
conn.connect();
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("email", "Your_Email")
.appendQueryParameter("password","Your_Password");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
code = conn.getResponseCode();
Log.e("Result", code + "");
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.e("Result",result.toString());
I'm trying to send some data from a JSP page to a PHP one (which should execute some code and return a success message).
I'm using this java function to make some tests:
public String excutePost(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
String urlParameters =
"var=" + URLEncoder.encode("varcontent", "UTF-8");
out.println(excutePost("remoteurl",urlParameters));
Now if i run the page i get the response "null" and none of the code in the php page is executed.
Am I doing something wrong? How can I allow the php page to run the code in it?
Isn't a simple echo $_POST['var'] enough to send the data back to the jsp page?
EDIT: I tried to see if the php page is receiving something by writing the posted variable in a file. But nothing is written in it.
$file = 'debug.txt';
echo file_put_contents($file, $_POST['var']);
and here is the exception i'm getting..
java.net.SocketException: Connection reset
No, an echo is not enough. Put $_POST['var'] in say a text file and serve the updated text file (Edit the text file each time you need to keep track of $_POST['var']). Alternatively you can put it in some DB and check for changes.
I'm trying to connect to the grooveshark API, this is the http request
POST URL
http://api.grooveshark.com/ws3.php?sig=f699614eba23b4b528cb830305a9fc77
POST payload
{"method":'addUserFavoriteSong",'parameters":{"songID":30547543},"header":
{"wsKey":'key","sessionID":'df8fec35811a6b240808563d9f72fa2'}}
My question is how can I send this request via Java?
Basically, you can do it with the standard Java API. Check out URL, URLConnection, and maybe HttpURLConnection. They are in package java.net.
As to the API specific signature, try sStringToHMACMD5 found in here.
And remember to CHANGE YOUR API KEY, this is very IMPORTANT, since everyone knows it know.
String payload = "{\"method\": \"addUserFavoriteSong\", ....}";
String key = ""; // Your api key.
String sig = sStringToHMACMD5(payload, key);
URL url = new URL("http://api.grooveshark.com/ws3.php?sig=" + sig);
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
OutputStream os = connection.getOutputStream();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
pw.write(payload);
pw.close();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
String response = sb.toString();
You could look into the Commons HttpClient package.
It is fairly straight forward to create POST's, specifically you could copy the code found here: http://hc.apache.org/httpclient-3.x/methods/post.html:
PostMethod post = new PostMethod( "http://api.grooveshark.com/ws3.php?sig=f699614eba23b4b528cb830305a9fc77" );
NameValuePair[] data = {
new NameValuePair( "method", "addUserFavoriteSong..." ),
...
};
post.setRequestBody(data);
InputStream in = post.getResponseBodyAsStream();
...
Cheers,
i'm looking for tutorial or quick example, how i can send POST data throw openStream.
My code is:
URL url = new URL("http://localhost:8080/test");
InputStream response = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
Could you help me ?
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setDoOutput(true);
connection.setDoInput(true);
// important: get output stream before input stream
OutputStream out = connection.getOutputStream();
out.write(content);
out.close();
// now you can get input stream and read.
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
writer.println(line);
}
Use Apache HTTP Compoennts http://hc.apache.org/httpcomponents-client-ga/
tutorial: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
Look for HttpPost - there are some examples of sending dynamic data, text, files and form data.
Apache HTTP Components in particular, the Client would be the best way to go.
It absracts a lot of that nasty coding you would normally have to do by hand