Android HttpPost从Youtube获取“无效的请求URI”

时间:2013-03-20 10:09:35

标签: android youtube http-post

我正在尝试访问此网址到Youtube(手机没有代理设置,直接上网)

  

http://gdata.youtube.com/feeds/api/videos/-/music?q=gagamv&max-results=50&alt=json&v=2

上面的URL我在任何PC浏览器中运行良好(将返回纯JSON字符串),即使我没有登录Youtube。

但我尝试通过Android的HttpPost访问此网址,只有我能获得无效的请求URI

这是我的代码:

    public static final String HEADER_TYPE="Content-Type";
    private static final String HEADER_TYPE_SET="application/text; charset=utf-8";
    public static final String HEADER_TYPE_2="Accept";
    private static final String HEADER_TYPE_SET_2="application/x-www-form-urlencoded";

    /** Socket操作逾時(3600秒) */
    public static final int TIMEOUT_SOCKET=7000;
    /** 連線逾時(3600秒) */
    public static final int TIMEOUT_CONECTION=7000;

    List<NameValuePair> params=new ArrayList<NameValuePair>();
    HttpParams httpP=null;
    DefaultHttpClient mHttpClient=null;
    UrlEncodedFormEntity entity=null;
    HttpResponse httpResp=null;
    String ret="";

    BasicHeader[] header=new BasicHeader[2];
    header[0]=new BasicHeader(HEADER_TYPE, HEADER_TYPE_SET);
    header[1]=new BasicHeader(HEADER_TYPE_2, HEADER_TYPE_SET_2);
    httpP=new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpP, TIMEOUT_CONECTION);
    HttpConnectionParams.setSoTimeout(httpP, TIMEOUT_SOCKET);
    String url=new String("http://gdata.youtube.com/feeds/api/videos/-/music?q=gagamv&max-results=50&alt=json&v=2");
    Log.d(Constants.TAG, "Youtube search URL: "+url);
    HttpPost post=new HttpPost(url);
    mHttpClient=new DefaultHttpClient(httpP);

    entity=new UrlEncodedFormEntity(params);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    httpResp=mHttpClient.execute(post);

    String status=httpResp.getStatusLine().toString();
    ret=new String(EntityUtils.toString(httpResp.getEntity(), "UTF-8"));

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

您需要使用HTTP GET请求。问题是您正在使用HTTP Post,并且当您使用get请求时,url将返回数据。

尝试以下代码(我已将缓冲区大小设置为4096,但您可以根据需要将其更改为动态):

        URL url = new URL("http://gdata.youtube.com/feeds/api/videos/-/music?q=gagamv&max-results=50&alt=json&v=2");
           HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
           try {
             InputStream in = new BufferedInputStream(urlConnection.getInputStream());
             byte buffer[] = new byte[4096];

             in.read(buffer);
             String str = new String(buffer);
             Log.d(TAG, " Data: " + str);

           } finally {
             urlConnection.disconnect();
           }