Android 通过GET方法发送值
我一直试图通过GET方法将数据发送到服务器,但我找不到一种方法来实现。我在异步任务中尝试了一些代码,但什么都没有。web服务采用cakePhp制作,格式如下:Android 通过GET方法发送值,android,Android,我一直试图通过GET方法将数据发送到服务器,但我找不到一种方法来实现。我在异步任务中尝试了一些代码,但什么都没有。web服务采用cakePhp制作,格式如下: Base_URI/users/add.json?json={“email”: xxx@x.com, “password”: “xxxxxxxxx”, “first_name”: “Xyz”, “last_name”: “Xyz”} String url = "Base_URI/users/add.json?json="; url
Base_URI/users/add.json?json={“email”: xxx@x.com, “password”: “xxxxxxxxx”, “first_name”: “Xyz”, “last_name”: “Xyz”}
String url = "Base_URI/users/add.json?json=";
url =url + URLEncoder.encode("{\"email\":\""+email+"\",\"password\":\""+password+"\"}", "UTF-8");
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;
在android中使用凌空库进行联网。您的字符串比较不正确 这会比较对象引用,不适用于您:
method == "POST"
Intead,使用equals():
您还可以执行以下操作:
method.equals("POST");
但如果method为null,则可能会导致错误。如果要使用method 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;
}
}
经过一整天的调试和尝试不同的解决方案,我终于解决了这个问题:) 我需要对参数部分进行编码,而不是对整个URL进行编码,如下所示:
Base_URI/users/add.json?json={“email”: xxx@x.com, “password”: “xxxxxxxxx”, “first_name”: “Xyz”, “last_name”: “Xyz”}
String url = "Base_URI/users/add.json?json=";
url =url + URLEncoder.encode("{\"email\":\""+email+"\",\"password\":\""+password+"\"}", "UTF-8");
谢谢大家的支持 发布您的代码,…我们将帮助修复它如果您确定应该使用JSON作为GET参数;正常名称-值对有什么问题。另外,您需要将JSON编码为base64,最后,我相信GET请求有255个字符的限制,但请不要引用我的话。此外,我不知道您是否开发了服务器实现,但最好不要通过GET请求发送电子邮件和密码。加密这两个参数并发布它们是一种更安全的方法。此处执行的请求是
POST
请求,而不是GET
请求。你确定这就是你想要的吗?@Halim不,我知道我必须使用namevaluepairs,但不知道如何在这里不需要使用任何第三方库。Android自带了org.apache.http
包,该包已经具备了执行OP所需的一切功能。Volley是Android中最新的网络。它可能非常简单,但它会在你的应用程序中增加不必要的负担,因为你可以使用内置方法,与OP想要的方法相比,使用内置方法并不复杂。也尝试了截击库,但这太难获取url格式。这不是问题所在。它工作得非常好。这里的问题是使用GET方法从给定的url解析json,根据您发布的代码,“is”将为null。它永远不会被设定。不会选择HTTP方法。错误记录在您的其他消息中,请确认。如果解析有问题,那是因为您正在解析null。我认为不可能通过HttpGet
方法发送Json
,它对我很有效,我在我的项目中使用了它。:)你试过了吗?看这个:;)我们可以伪造一些东西D如果它不起作用,我不能分享。呵呵