I'm trying to make an app that can download mp3 files by a youtube url.
I did some research on the youtube-mp3.org api and this is the way I think it should be done:
Get http://www.youtube-mp3.org/api/pushItem/?item=http://www.youtube.com/watch?v=xo9EV3A4oaA&xy=yx
Step 1 returns an ID, which you have to use in the following request: "http://www.youtube-mp3.org/api/itemInfo/?video_id=" + ID
Step 2 returns another code, which you have to use in this request: "http://www.youtube-mp3.org/get?video_id=xo9EV3A4oaA&h=" + <code from step 2>
Step 3 retruns the mp3.
Unfortunately, my code already fails at step 1: I'm getting a 404, page not found.
Here's my code (only for step 1):
private DefaultHttpClient createHttpClient() {
HttpParams my_httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(my_httpParams, 3000);
HttpConnectionParams.setSoTimeout(my_httpParams, 15000);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ThreadSafeClientConnManager multiThreadedConnectionManager = new ThreadSafeClientConnManager(my_httpParams, registry);
DefaultHttpClient httpclient = new DefaultHttpClient(multiThreadedConnectionManager, my_httpParams);
return httpclient;
}
private class DownloadVid extends AsyncTask<Void, Void, Void> {
int mStatusCode = 0;
String content = "";
#Override
protected Void doInBackground(Void... args) {
String url = "http://www.youtube-mp3.org/api/pushItem/?item=http://www.youtube.com/watch?v=xo9EV3A4oaA&xy=yx";
DefaultHttpClient httpclient = createHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.addHeader("Accept-Location", "*");
try {
HttpResponse response = httpclient.execute(httpget);
StatusLine statusLine = response.getStatusLine();
mStatusCode = statusLine.getStatusCode();
if (mStatusCode == 200){
content = EntityUtils.toString(response.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
mStatusCode = 0;
} catch (IOException e) {
e.printStackTrace();
mStatusCode = 0;
} catch (IllegalStateException e){
e.printStackTrace();
mStatusCode = 0;
}
return null;
}
#Override
protected void onPostExecute(Void arg) {
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this, "Result=" + content + " StatusCode=" + mStatusCode, Toast.LENGTH_LONG).show();
}
}
I'm not sure why it isn't working. Any ideas?
Encode the item parameter, like this:
String item = URLEncoder.encode("http://www.youtube.com/watch?v=xo9EV3A4oaA", "utf-8");
String url = "http://www.youtube-mp3.org/a/pushItem/?item="+item+"&xy=yx";
Or like this:
Uri uri = new Uri.Builder()
.scheme("http")
.authority("www.youtube-mp3.org")
.path("/a/pushItem/")
.appendQueryParameter("item", "http://www.youtube.com/watch?v=xo9EV3A4oaA")
.appendQueryParameter("xy", "yx")
.build();
Related
I am trying to use this method i also tried to impot libriries but all in vain. Kindly help me. Not any HTTPClient library is showing on my andriod studio. Help would be appreciated
public String getHttpPost(String url,ContentValues) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
Oh!Still you are using HttpClient.You can use HttpURLConnection,Volley etc. HttpClient class is now deprecated.Also add Internet permission, and dependensies in gradle file.
HttpURLConnection urlConnection = null;
try {
URL urlToRequest = new URL(_url);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(30000);
urlConnection.setReadTimeout(30000);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
if (_authenticationKey != null) {
urlConnection.setRequestProperty(_authenticationKey, _authenticationValue);
}
if (_jsonPacket != null) {
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(_jsonPacket);
wr.flush();
}
int statusCode = urlConnection.getResponseCode();
JSONObject job;
if (statusCode != HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getErrorStream());
String responseString = getResponseString(in);
if (isJSONValid(responseString)) {
job = new JSONObject(responseString);
return new PostingResult(job, Constants.IntegerConstants.failureFromWebService, "");
} else {
return new PostingResult(null, statusCode, Constants.StringConstants.serverCommunicationFailed + "Response code = " + statusCode);
}
} else {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String responseString = getResponseString(in);
if (isJSONValid(responseString)) {
job = new JSONObject(responseString);
return new PostingResult(job, Constants.IntegerConstants.success, "");
} else {
return new PostingResult(null, statusCode, Constants.StringConstants.serverCommunicationFailed + Constants.StringConstants.serverReadingResponseFailed);
}
}
You can use "Volley" library to make network call.
eg.
Add this line in build.gradle (Module:app)
compile 'com.mcxiaoke.volley:library:1.0.19'
As you are making network call you need internet permission. So add Internet permission line in Manifest.xml
Now you need to write a small method inside your class where you need to make network call and need to pass Hashmap to it. Hashmap contains all your post parameters.
private void getJSONResponse(HashMap<String, String> map, String url) {
pd.show();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(map), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Mayur", "Response : " + response);
//tv_res.setText(response.toString());
//pd.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error Occured", Toast.LENGTH_SHORT).show();
//tv_res.setText("ERROR");
//pd.dismiss();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(20000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));Volley.newRequestQueue(this).add(request);}
Now in your onCreate method or any other method just create a Hashmap of post parameters and pass it to this method with post url.
eg.
HashMap<String, String> map = new HashMap<String, String>();
map.put("fname", "Mayur");
map.put("lname", "Thakur");
getJSONResponse(map,<your url>);
I have a web server, where i log in in my android Application, after that loging i recive as an XML the user who logged with a field named token.
This token is used to keep open the session during next calls to webService, and it works sendidnt the token as a cookie named "acrsession" but it seems not working because everytime i tried to check if im logged in (using a get call named currentUser) it returns me forbidden, so i think it isnt working good.
Here is my AsyncTask class who do the calls to server.
public String getFileName() {
return FileName;
}
public void setFileName(String fileName) {
FileName = fileName;
}
private String Response;
private URI uriInfo;
private String FileName;
public WebServiceTask(int taskType, Context mContext, String processMessage,String token) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
this.token=token;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
public void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
//hideKeyboard();
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
this.Response=response;
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
int responseCode=0;
// Create a local instance of cookie store
//CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
//HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
//localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//CookieManager cookieManager= CookieManager.getInstance();
this.getLocalContext();
this.cookieStore.addCookie(new BasicClientCookie("acrsession", this.token));
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
int executeCount = 0;
do
{
pDlg.setMessage("Logging in.. ("+(executeCount+1)+"/5)");
// Execute HTTP Post Request
executeCount++;
response = httpclient.execute(httppost,localContext);
responseCode = response.getStatusLine().getStatusCode();
// If you want to see the response code, you can Log it
// out here by calling:
// Log.d("256 Design", "statusCode: " + responseCode)
} while (executeCount < 5 && responseCode == 408);
uriInfo = httppost.getURI();
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget,localContext);
responseCode = response.getStatusLine().getStatusCode();
httpget.getRequestLine();
uriInfo = httpget.getURI();
break;
case PUT_TASK:
HttpPut httpput = new HttpPut(url);
File file = new File(this.FileName);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httpput.setEntity(reqEntity);
response = httpclient.execute(httpput,localContext);
responseCode = response.getStatusLine().getStatusCode();
httpput.getRequestLine();
uriInfo = httpput.getURI();
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
this.Response=total.toString();
return total.toString();
}
public String getResponse(){
return this.Response;
}
public HttpContext getLocalContext()
{
if (localContext == null)
{
localContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
localContext.setAttribute(ClientContext.COOKIE_ORIGIN, cookieStore);
localContext.setAttribute(ClientContext.COOKIE_SPEC, cookieStore);
localContext.setAttribute(ClientContext.COOKIESPEC_REGISTRY, cookieStore);
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);// to make sure that cookies provided by the server can be reused
}
return localContext;
}
Plesae tell me what im doing bad.
Thanks in advance.
Well, finally i found the solution, everything was ok but i fortgot to set cookie Domain and path, so onced i putted it it worked.
Now cookie creation looks like this:
this.localContext=this.getLocalContext();
BasicClientCookie cookie = new BasicClientCookie("acrsession", this.token);
cookie.setDomain(this.Domain);
cookie.setPath(this.path);
this.cookieStore.addCookie(cookie);
localContext.setAttribute(ClientContext.COOKIE_STORE, this.cookieStore);
Hope it will help someone else.
I have an app android that in an AsyncTask make 2 get request to a servlet.
I want to retrieve a String that contains a simple response.
This is my AsyncTask:
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
String responseStr = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
try {
HttpClient client = new DefaultHttpClient();
URI getURL = new URI("http://192.168.1.101:8080/MusaServlet?collection="+collection+"&name="+filename);
Log.i("QUERY",getURL.getQuery());
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
responseStr = EntityUtils.toString(responseGet.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseStr;
}
Instead the servlet code is:
PrintWriter out = response.getWriter();
out.println("HELLO STUPID APP!");
However the dialog showed by app is empty! No words!
What's the problem guys?
Thank's
At first check your GET request status code as
responseGet.getStatusLine().getStatusCode();
If is giving number 200 then GET is successfull.
Now if is 200 then you will get the response what you have sent by following code
HttpEntity resEntityGet = responseGet.getEntity();
and then
String result;
if(resEntityGet !=null ){
result= EntityUtils.toString(resEntityGet);
}
Now the most important thing is once you perform responseGet.getEntity() the data of GET response will be passed to the variable.. you assign.. and later on calling responseGet.getEntity() will always return empty...
That may be the reason you are getting empty response in your dialog
EDIT:
Ok I have modified my code and playing with logcat I'm sure that the responseCode is not 200.
What is the problem now? -.-"
I'm connecting my Application to a REST type webservice. I'm using the apache http library, the request is a standard post request, ran in a background thread.
Now my problem is that if I'm using
http://myserver.com/api/command
it works and I get the proper response, but the same url with https:
https://myserver.com/api/command
I get an empty response. The http header is even 200 OK.
BOTH of these work on 2.0.3 but not on 4.0.3. On 4.0.3 the API seems to work only if I use plain http, with https I get empty responses.
This is the code:
#Override
protected HttpResponse doInBackground(String... params) {
String link = params[0];
HttpClient client = createHttpClient();
try {
HashMap<String, ContentBody> files = ApiManager.getFiles();
MultipartEntity mpEntity = new MultipartEntity();
if(files != null) {
for(String i : files.keySet()) {
ContentBody k = files.get(i);
mpEntity.addPart(i, k);
}
}
if(this.callParameters != null) {
for(NameValuePair i : this.callParameters) {
StringBody sb = new StringBody((String)i.getValue(),"text/plain",Charset.forName("UTF-8"));
mpEntity.addPart(i.getName(), sb);
}
}
httppost.setEntity(mpEntity);
// Execute HTTP Post Request
Log.d("ApiTask","Executing request: "+httppost.getRequestLine());
HttpResponse response = null;
response = client.execute(httppost);
client.getConnectionManager().shutdown();
return response;
}
catch(UnknownHostException e) {
exception = e;
return null;
}
catch (IOException e) {
exception = e;
return null;
}
catch(Exception e) {
return null;
}
}
#Override
protected void onPostExecute(HttpResponse result) {
System.out.println("STATUS:"+result.getStatusLine());
try {
StringBuilder responseText = this.inputStreamToString(result.getEntity().getContent());
System.out.println("RESPONSE:"+responseText);
}
catch(Exception e) {
System.out.println("Error");
}
}
private HttpClient createHttpClient() {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
return new DefaultHttpClient(conMgr, params);
}
Thank you in advance
I constructed an HttpClient, and set timeout parameters.
the code is like this:
while(bufferedinputstream.read()!=-1){
post.setEntity(multipartEntity);
HttpResponse response = httpClient.excute(post);
}
it worked fine for the first several request, and then somehow the response is not returned, and no exception or timeout exception was thrown. Anyone has any idea what's happening?
since you re not getting any errors or exceptions (do you print them out?), you could check the satusCode of your response. Maybe it helps.
(overridden method from my AsyncTask)
protected String doInBackground(String... arg) {
String url = arg[0]; // Added this line
//...
Log.i(DEBUG_TAG, "URL CALL -> " + url);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String mResponse = "";
try {
List<NameValuePair> params = new LinkedList<NameValuePair>();
//...
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse mHTTPResponse = client.execute(post);
StatusLine statusLine = mHTTPResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { //
//get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
mHTTPResponse.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = rd.readLine()) != null) {
builder.append(aux);
}
mResponse = builder.toString();
} else {
//cancel task and show error
Log.e(DEBUG_TAG, "ERROR in Request:" + statusCode);
this.cancel(true);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mResponse;
}