通过GET方法发送值

时间:2014-01-18 19:38:25

标签: android

我一直在尝试通过GET方法向服务器发送数据,但我无法找到办法。我在异步任务中尝试了很少的代码,但没有。 Web服务是在cakePhp中制作的,格式如下:

Base_URI/users/add.json?json={“email”: xxx@x.com, “password”: “xxxxxxxxx”, “first_name”: “Xyz”, “last_name”: “Xyz”}

要求Android专家找出摆脱这个问题的方法。感谢

以下是代码:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("email", UserDummy.email));
            nameValuePairs.add(new BasicNameValuePair("password", UserDummy.password));
            nameValuePairs.add(new BasicNameValuePair("first_name", UserDummy.fname));
            nameValuePairs.add(new BasicNameValuePair("last_name", UserDummy.lname));
            // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
            url += "?json={" + paramString+"}";                                                                                                                                                     ;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        Log.v("XXX", e.getMessage());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        Log.v("XXX", e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        Log.v("XXX", e.getMessage());
    }

    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 JSON String
    return jObj;

HttpGet不接受这种url格式并且给出错误但是当我在浏览器上尝试它时它工作正常。错误如下:

Illegal character in query at index 56

4 个答案:

答案 0 :(得分:3)

最后经过调试并尝试了一整天不同的解决方案后,我解决了问题:)

我需要对参数部分进行编码,而不是像这样对整个URL进行编码:

String url = "Base_URI/users/add.json?json=";
    url =url +  URLEncoder.encode("{\"email\":\""+email+"\",\"password\":\""+password+"\"}", "UTF-8");

感谢大家的支持!

答案 1 :(得分:0)

在android中使用volley库进行联网。

答案 2 :(得分:0)

你的字符串比较不对。

这会比较对象引用,但不适合您:

method == "POST"

Intead,使用equals():

"POST".equals(method);

你也可以这样做:

method.equals("POST");

但如果method为null,则可能导致错误。

答案 3 :(得分:0)

如果你想使用方法GET:

此方法可以帮助您

/**
 * 
 * @param url stands for API
 * @param 
 *      params[i][0] stands for column's name
 *      params[i][1] stands for value which respective with column's name
 * @return InputStream which got from Server
 */
public static int sendJSONObject(IGetUserData iUserId, String method, String url, String[]... params) {
    InputStream mInputStream = null;
    HttpClient mHttpClient = null;
    HttpRequestWithEntity mHttpGet = null;
    int status = Def.REQUEST_INVALID;
    try {
        mHttpClient = new DefaultHttpClient();

        mHttpGet = new HttpRequestWithEntity(url, method);

        JSONObject mObject = new JSONObject();
        for (String[] pair : params) {
            mObject.put(pair[0], pair[1]);
        }

        StringEntity mStringEntity = new StringEntity(mObject.toString());
        mStringEntity.setContentEncoding("UTF-8");
        mStringEntity.setContentType("application/json");

        mHttpGet.setEntity(mStringEntity);          
        HttpResponse mResponse = mHttpClient.execute(mHttpGet);
        status = mResponse.getStatusLine().getStatusCode();

        Log.d(TAG, "status: " + status);
        if (mResponse != null && 
                (status == Def.CREATED || status == Def.OK)) {
            mInputStream = mResponse.getEntity().getContent();  
            if(mInputStream != null){
                String json = StreamUtils.converStreamToString(mInputStream);
                userId = JSONUtils.getUserId(json);
                iUserId.sendUserId(userId);
                Log.d("viet","userid = " + userId);
            }
        }

    } catch (Exception e) {
        Log.e(TAG, "Error during send");
        status = Def.NETWORK_ERROR;
    }
    return status;
}

这就是你需要的。

    mHttpClient = new DefaultHttpClient();

    mHttpGet = new HttpRequestWithEntity(url, method);

    JSONObject mObject = new JSONObject();
    for (String[] pair : params) {
        mObject.put(pair[0], pair[1]);
    }

    StringEntity mStringEntity = new StringEntity(mObject.toString());
    mStringEntity.setContentEncoding("UTF-8");
    mStringEntity.setContentType("application/json");

    mHttpGet.setEntity(mStringEntity);          
    HttpResponse mResponse = mHttpClient.execute(mHttpGet);

这里是 HttpRequestWithEntity.java

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

public class HttpRequestWithEntity extends HttpEntityEnclosingRequestBase {

    private String method;

    public HttpRequestWithEntity(String url, String method) {
        if (method == null || (method != null && method.isEmpty())) {
            this.method = HttpMethod.GET;
        } else {
            this.method = method;
        }
        try {
            setURI(new URI(url));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getMethod() {
        return this.method;
    }

}