通过GET方法发送值
我一直试图通过GET方法发送数据到服务器,但我无法找到一种方法来做到这一点。我在异步任务中尝试过几个代码,但没有任何代码Web服务在CakePHP执行和格式是这样的:请通过GET方法发送值
Base_URI/users/add.json?json={“email”: [email protected], “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中使用volley lib进行网络连接。
这里没有必要使用任何第三方库。 Android自带了内置的org.apache.http包,它已经拥有了所有需要的东西来完成OP所需的任务。 –
Volley是Android中最新的网络连接。它很简单 –
也许,但它会增加应用程序中不必要的重量,因为您可以使用内置方法,与OP所需的方法相比,使用方法并不复杂。 –
您的字符串比较不正确。
与此相比对象引用,并不会为你工作:
method == "POST"
这一翻译,使用equals()方法:
"POST".equals(method);
你也可以这样做:
method.equals("POST");
但如果方法为空,可能会导致错误。
这不是问题。它的工作非常好。这里的问题是通过GET方法从给定的URL解析json – Shahzeb
根据你发布的代码,“is”将为空。它永远不会被设置。不会选择HTTP方法。您的其他消息中的错误日志证实了这一点。如果解析出现问题,那是因为您解析为空。 – MikeHelland
如果你想使用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;
}
}
我不这么认为可以通过'HttpGet'方法发送'Json', –
它适用于我,我在我的项目中使用它。 :) 你试过了吗? – Luc
看到这个:http://stackoverflow.com/questions/6073896/sending-json-object-to-the-server-via-http-get –
发布您的代码,...我们将帮助您解决它 – petey
您确定您应该使用JSON作为GET参数;正常名称 - 值对有什么问题。此外,您需要将该JSON编码为base64,最后,我相信GET请求上有255个字符的限制,但请不要在此引用我的意思。 –
另外,我不知道你是否开发了服务器实现,但最好不要通过GET请求发送电子邮件和密码。加密这两个参数并将它们发布是一种更安全的方法。 –