gpt4 book ai didi

android - 通过 GET 方法发送值

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:11:20 24 4
gpt4 key购买 nike

我一直在尝试通过 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

最佳答案

终于在一整天的调试和尝试不同的解决方案之后,我解决了这个问题:)

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

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

感谢大家的支持!

关于android - 通过 GET 方法发送值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21208922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com