如何使用多个参数调用http post requst。
像这样 WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
webClient.UploadStringAsync(new Uri(URL), "POST", JSON);
这个在c#中。但我想在android
我已经尝试过这个
了 public String postServiceCall(String paraURL,JSONArray jsonParams, String usrId, String syncDt){
TAG = "makeHttpRequestJSONObject";
Log.d(MODULE, TAG + " called");
String json = "";
InputStream is = null;
try{
HttpParams httpParams = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
String params = "UserId="+ usrId +"&SyncDate="+syncDt;
String encodedUrl = URLEncoder.encode (params,"UTF-8");
HttpPost httpPost = new HttpPost(paraURL+encodedUrl);
httpPost.setHeader( "Content-Type", "application/json" );
Log.v(MODULE, TAG + ", POST paraURL " + (paraURL+encodedUrl));
Log.v(MODULE, TAG + ", POST paraURL jsonParams.toString() " + (jsonParams.toString()));
httpPost.setEntity(new ByteArrayEntity(jsonParams.toString().getBytes("UTF8")));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
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().trim();
json = json.substring(1,3);
Log.v(MODULE, TAG + ", json data " + json);
} catch (Exception e){
Log.e(MODULE, TAG + "Exception Occurs " + e);
json = "";
}
return json;
}
}
此代码无法正常运行。这段代码只发布了json。这里userid和syncdate不发送到服务器端
答案 0 :(得分:0)
请检查
String encodedUrl = URLEncoder.encode (params,"UTF-8");
示例 你的代码会像这样返回网址
输入“http://test.com/ttttt?query=jjjj test” 输出“http://test.com/ttttt?query=jjjj+test”
但你需要这样的网址
输出“http://test.com/ttttt?query=jjjj%20test”
所以你可以尝试这个功能进行网址编码
public String parseUrl(String surl) throws Exception
{
URL u = new URL(surl);
return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}
OR
这可以帮助您适应更高版本
public String parseURL(String url, Map<String, String> params)
{
Builder builder = Uri.parse(url).buildUpon();
for (String key : params.keySet())
{
builder.appendQueryParameter(key, params.get(key));
}
return builder.build().toString();
}