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,
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 want to do an online xml request in java but the server responds with 401 error that means that there is an authentication that is need to access the server. I have the certfile.cer that i can use to do the authentication but i dont know how to load it in java.How can I achieve this in java? Here is part of my code.
StringBuilder answer = new StringBuilder();
URL url = new URL("www.myurl.com");
URLConnection conn = url.openConnection();
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(xml);
writer.flush();
String line;
while ((line = reader.readLine()) != null)
{
answer.append(line);
}
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());
}
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
What is the best way to use preemptive basic http authentication using HttpUrlConnection. (Assume for now I can't use HttpClient).
EDIT for clarification: I'm setting the un/pw correctly in the request header using Base64 encoding. Are there any additional flags or properties that need to be set, or is the fact that I'm setting the basic auth headers for the request all that is needed for preemptive basic auth?
If you are using Java 8 or later, java.util.Base64 is usable:
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
String encoded = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8)); //Java 8
connection.setRequestProperty("Authorization", "Basic "+encoded);
Then use the connection as normal.
If you're using Java 7 or lower, you'll need a method to encode a String to Base64, such as:
byte[] message = (username+":"+password).getBytes("UTF-8");
String encoded = javax.xml.bind.DatatypeConverter.printBase64Binary(message);
Yes, that's all you have to do in order to use Basic Auth. The code above to set the Request Property should be done immediately after opening the connection and before getting the Input or Output streams.
Incidentally, in case someone else runs into the same, the android problem, is also present if you use org.apache.commons.codec.binary.Base64 and do Base64.encodeBase64String(). You need to do Base64.encodeBase64() and get a byte[] then construct the string.
It caught me offguard entirely that the results would be different for the line ending between those two methods.
You can use java.net.Authenticator to configure basic auth. globally for every request send by your application, see :
http://docs.oracle.com/javase/7/docs/technotes/guides/net/http-auth.html
http://developer.android.com/reference/java/net/Authenticator.html#getPasswordAuthentication()
you need to do this just copy paste it be happy
HttpURLConnection urlConnection;
String url;
// String data = json;
String result = null;
try {
String username ="danish.hussain#gmail.com";
String password = "12345678";
String auth =new String(username + ":" + password);
byte[] data1 = auth.getBytes(UTF_8);
String base64 = Base64.encodeToString(data1, Base64.NO_WRAP);
//Connect
urlConnection = (HttpURLConnection) ((new URL(urlBasePath).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "Basic "+base64);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10000);
urlConnection.connect();
JSONObject obj = new JSONObject();
obj.put("MobileNumber", "+97333746934");
obj.put("EmailAddress", "danish.hussain#dhl.com");
obj.put("FirstName", "Danish");
obj.put("LastName", "Hussain");
obj.put("Country", "BH");
obj.put("Language", "EN");
String data = obj.toString();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}else {
// return new String("false : "+responseCode);
new String("false : "+responseCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
I was having this problem too.
And Now I have solved this problem.
My code is :
URL url = new URL(stringUrl);
String authStr = "MyAPIKey"+":"+"Password";
System.out.println("Original String is " + authStr);
// encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(authStr .getBytes());
String authEncoded = new String(bytesEncoded);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Basic "+authEncoded);
It may help many others.
Best of luck.
Regarding the Base64 encoding problem, I found this library: http://sourceforge.net/projects/migbase64/
I have not fully vetted it but I am using it for the Basic Authentication solution shown above (as well as for image encoding/decoding), and it works well. It provides a parameter for whether or not to include the newline.