在Android中发出POST请求

时间:2014-02-03 18:48:46

标签: java android post

我正在尝试向POST应用中的服务器发出Android请求,但它没有发生。以下是代码 -

try{

        View p = (View) v.getRootView();

        EditText usernamefield = (EditText)p.findViewById(R.id.username);
        String username = usernamefield.getText().toString();
        EditText passwordfield = (EditText)p.findViewById(R.id.pass);
        String password = passwordfield.getText().toString();

        String apiKey = "ac96d760cb3c33a1ee988750b0b2fd12";
        String secret = "cd9118e8d1d32d003e0ed54a202c2bf8";

        Log.i(TAG,password);

        String authToken = computeMD5hash(username.toLowerCase()).toString()+computeMD5hash(password).toString();
        String authSig = computeMD5hash("api_key"+apiKey+"authToken"+authToken+"method"+"auth.getMobileSession"+"username"+username+secret).toString();

        Log.i(TAG,authToken);

        HttpClient client = new DefaultHttpClient();
        Log.i(TAG,"after client1");
        HttpPost post = new HttpPost("http://ws.audioscrobbler.com/2.0/");
        Log.i(TAG,"after client2");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
        nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
        nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
        nameValuePairs.add(new BasicNameValuePair("format", "json"));
        nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
        nameValuePairs.add(new BasicNameValuePair("username", username));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        Log.i(TAG,post.getURI().toString()); //logs the URL
        HttpResponse response = client.execute(post);

        int status = response.getStatusLine().getStatusCode();
        Log.i(TAG,"Status code is"+status);

        Log.i(TAG,"after post");

        InputStream ips  = response.getEntity().getContent();
        BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
        if(response.getStatusLine().getStatusCode()!= org.apache.commons.httpclient.HttpStatus.SC_OK)
        {
            Log.i(TAG,"bad http response");
            Toast.makeText(getApplicationContext(),"bad httpcode",Toast.LENGTH_LONG).show();
            throw new Exception(response.getStatusLine().getReasonPhrase());
        }
        StringBuilder sb = new StringBuilder();
        String s;
        while(true)
        {
            s = buf.readLine();
            if(s==null || s.length()==0)
                break;
            sb.append(s);

        }
        buf.close();
        ips.close();
     System.out.print(sb.toString());
    }
    catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    catch(NoSuchAlgorithmException e)
    {

    }
    catch(Exception e){

    }

代码执行到Log.i(TAG,post.getURI().toString())日志语句。它会打印出来的网址 - http://ws.audioscrobbler.com/2.0/。没有附加参数(这很奇怪)。

我不知道使用NameValuePairs将参数添加到URL的实现有什么问题。

3 个答案:

答案 0 :(得分:1)

我有一个简单的方法将数据发布到服务器。请使用它并告诉我这是否对您有用:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
nameValuePairs.add(new BasicNameValuePair("format", "json"));
nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
nameValuePairs.add(new BasicNameValuePair("username", username));
//call to method
JSONObject obj = makeHttpRequest(nameValuePairs, "http://ws.audioscrobbler.com/2.0/", "POST");

public static JSONObject makeHttpRequest(List<NameValuePair> params, String url, String method) {
        InputStream is = null;
        JSONObject jObj = null;
        String json = "";
        // Making HTTP request
        try {
            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient            
                url = url.trim();
                Log.e("FETCHING_DATA_FROM",""+url.toString());
                HttpPost httpPost = new HttpPost(url);

                HttpParams httpParameters = new BasicHttpParams();
                // Set the timeout in milliseconds until a connection is established.
                int timeoutConnection = 600000;
                HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                // Set the default socket timeout (SO_TIMEOUT) 
                // in milliseconds which is the timeout for waiting for data.
                int timeoutSocket = 600000;
                HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);       
                DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);


                httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }else if(method == "GET"){
                // request method is GET

                if(params!=null){
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                }

                HttpGet httpGet = new HttpGet(url);
                Log.e("FETCHING_DATA_FROM",""+url.toString());

                HttpParams httpParameters = new BasicHttpParams();
                // Set the timeout in milliseconds until a connection is established.
                int timeoutConnection = 600000;
                HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                // Set the default socket timeout (SO_TIMEOUT) 
                // in milliseconds which is the timeout for waiting for data.
                int timeoutSocket = 600000;
                HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);       
                DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace(); 
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();

        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        return jObj;
    }   

答案 1 :(得分:0)

您必须将此代码包装在try catch块中,因为此处抛出了几个可能的异常。至于哪个是我不确定的问题,但是这里有一些可能导致问题的常见问题,你需要提供更多信息才能看到它是哪一个: 1)在较新版本的Android上,如果你在主UI线程中进行thisw调用,它将抛出一个例外NetworkOnMainThread异常。您必须在后台线程上执行网络代码。 2)您没有在清单中声明Internet权限,因此会引发安全性异常。

您需要查看logcat中的try / catch的catch部分中的异常或中断。如果您的捕获物如下:

catch(Exception e)
{
}

然后它会默默地吃掉异常并且没有给出任何问题的迹象。

答案 2 :(得分:0)

试试JsonStringer.Like:

HttpPost request = new HttpPost("http://ws.audioscrobbler.com/2.0/something_here");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONStringer vm;
try {
     vm = new JSONStringer().object().key("method")
    .value("auth.getMobileSession").key("api_key").value(apikey)
    .key("api_sig")          .value(authSig).key("format").value("json").key(authToken).value(authToken).key("username").value(username)
    .endObject();
StringEntity entity = new StringEntity(vm.toString());
request.setEntity(entity);
 HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);

同样,Kaediil说使用你的回复代码制作try和catch子句。